当前位置:网站首页>Actual combat: basic use of Redux
Actual combat: basic use of Redux
2022-07-01 05:21:00 【Zhou Xue zzz】
redux Data flow
Overall process
Initialization project
establish react
npm i create-react-app -g
create-react-app react-redux-demo
add to react-redux
npm i redux --save
npm i react-redux --save
Project directory structure :
- [ Container components ] Connect [ Display components ] and [store]
- Display components 《=》 Container components connect《=》store
To write store
// demo-react-redux/src/redux/actions/countAction.js
export const Add = {
type:'add'
}
export const Sub = {
type:'sub'
}
// demo-react-redux/src/redux/reducers/counter.js
const initialState = {
count: 0,
}
export default function counterReducer(state = initialState, action) {
switch (action.type) {
case 'add': return Object.assign({
}, state, {
count: state.count + 1
});
case 'sub': return Object.assign({
}, state, {
count: state.count - 1
});
default: return state;
}
}
// demo-react-redux/src/redux/reducers/index.js
import {
combineReducers } from 'redux' // Native api
import counter from './counter' // Customize reducer
const reducers = combineReducers({
counter
})
export default reducers
Container components
// demo-react-redux/src/containers/index1.count.js
import {
connect } from 'react-redux'
import {
Add,Sub} from "../redux/actions/countAction";
import counter from '../pages/counter' // Display components
const mapStateToProps = state => {
return {
count: state.counter.count,
}
}
const mapDispatchToProps = dispatch => {
return {
countAdd: (count) => {
dispatch(Add) // dispatch Trigger action
},
countSub: (count)=> {
dispatch(Sub)
}
}
}
/** * connect effect * 1. Components counter adopt mapStateToProps, Use props.count Read state Value * 2. Components counter adopt mapDispatchToProps, Use props.countAdd()/props.countSub() modify state value */
const App = connect(
mapStateToProps,
mapDispatchToProps
)(counter)
export default App;
Display components
// demo-react-redux/src/pages/counter.jsx
export default function Counter(props){
return (
<div style={
{
textAlign: 'center'}}>
<p>count: {
props.count}</p>
<p>
<button onClick={
props.countAdd}>+</button>
<button onClick={
props.countSub}>-</button>
</p>
</div>
)
}
Entrance file
// react-reudx
import {
Provider } from 'react-redux'
import {
createStore } from 'redux'
import reducers from './redux/reducers'
// demo:counter
import App from './containers/index1.count';
const store = createStore(reducers)
ReactDOM.render(
<Provider store={
store}>
<App />
</Provider>
, document.getElementById('root')
);
verification
start-up : npm run start
demo-simple: useselect+usedispatch
export default function Counter(){
// obtain state: amount to mapStateToProps
const count = useSelector(state => state.counter.count);
// modify state: amount to mapDispatchToProps
const dispatch = useDispatch();
return (
<div style={
{
textAlign: 'center'}}>
<h1>CounterExpand: {
count}</h1>
<p>
<button onClick={
()=>{
dispatch(Add)}}>+</button>
<button onClick={
()=>{
dispatch(Sub)}}>-</button>
</p>
</div>
)
}
demo-message
Examples of more complex data types {id, label, value}
// demo:message Object contains id,lable,value Equal attribute
// import App from './containers/index2.message';
// demo:message + useselect + usedispatch
import App from './pages/MessageExpand';
Redux DevTools Tools
chrome Plug in tools
https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd
step :
- install Redux DevTools
- Add a line to the code @demo-react-redux/src/index.js
// Before
const store = createStore(reducers)
// Now?
const store = createStore(
reducers, /* preloadedState, */
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
redux-api
react-redux: useSelector and useDispatch
Equivalent to a simplified version of connect , advantage
- Easy to use
- Container components can be omitted , Use directly in the rendering component state and dispatch
- useSelector amount to mapStateToProps, For component reading state
- useDispatch amount to mapDispatchToProps, Used for component calls dispatch, modify state
- Available version :react-redux 7.1
// useSelector Example
// grammar :const result : any = useSelector(selector : Function, equalityFn? : Function)
import {
useSelector } from 'react-redux'
const counter = useSelector(state => state.counter)
// useDispatch Example
import {
useDispatch } from 'react-redux'
const dispatch = useDispatch();
<button onClick={
() => dispatch({
type: 'increment-counter' })}>
Increment counter
</button>
Deepen understanding useSelector
- mapStateToProps Only objects can be returned , and useSelect Get any type
- useSelector monitor : When dispatched(action) when ,useSelector The previous selector The result is shallow compared with the current result . If different , will re-render
- Batch update : Multiple calls within a component useSelector, Each call creates redux store A single subscription to . and react-reduxv7 The version uses react A lot of (batching) Update behavior , So even if many times useSelector Return value , It's just re-render once
useDispatch Be careful ( To be verified )
- Use the callback with dispatch When passed to a subcomponent
- It is recommended to use for callback useCallback,
- Because otherwise , Due to changed reference , Subcomponents may render unnecessarily .
// Use useCallback
const incrementCounter = useCallback(
() => dispatch({ type: 'increment-counter' }),
[dispatch]
)
// Pass to subcomponent
<MyIncrementButton onIncrement={incrementCounter} />
react-redux: connect
grammar :
connect([mapStateToProps], [mapDispatchToProps],[mergeProps], [options])(cmp)
- Higher order function , Accept parameters as functions , The return value is also a function
- cmp It's for connect Return the parameters of the function , It is generally a component
function :
- Connect React Components and Redux store, hold Redux Productive state Pass it to the component
- The connection operation will not change the original component class , Instead, return to the new and Redux store Connected component class
- Just inject dispatch, No monitoring store
mapStateToProps
- Personal understanding : Component read state data
- function : Essential function . Build from the outside state Object to UI Component's props Object mapping
- Use :( Container components state )=> {return UI Components props} Returns the object , Each key value pair is a pair of mappings
mapDispatchToProps
Personal understanding : Component write state data
- function : The essence is a function or object , establish UI Component parameters to store.dispatch Mapping of methods
- Parameters : dispatch and ownProps( Of the container component props object )
- return :kv Yes , among v Is the function
react-redux: provider Components
What is it? ?
- react-redux Components provided , On the outermost layer of the root component ,App All sub components can be obtained by default state
- Help maintain store, You can get the container components to state.
function :
- receive store, take store Bound to the childContext On
- When store When something changes , to update store
principle :
- React Component's context attribute ,store Put in context object context above .
- The subcomponents can be downloaded from context Get store
redux:store
What is it? ?
- Container for saving data
- The whole application can only have one Store
Use
- createStore: Reducer As a parameter , Generate a new Store.
- store.dispatch: Send new Action,[ Automatically ] call Reducer Get new State
api
- getState(): obtain state
- dispatch(action): to update state
- subscribe(listener): Register listener
createStore(reducer, [initialState])
- reducer(Function): Receive two parameters , At present state Trees and what to deal with action, Return to new state Trees
- [initialState] (any): In the beginning state.
- If you use combineReducers establish reducer, It must be associated with the incoming keys( The caller ) Keep the same structure
redux:Action
The essence :object type ,type Property is a must , Express Action name , It's equivalent to instructions
function :View issue dispatch =》 Auto trigger corresponds to reducer =》 State change =》 view Change again
- Sync :Action After sending out ,Reducer Immediately calculate State;
- asynchronous :Action After sending out , I'll do it later Reducer.
store.dispatch({
type: 'ADD_TODO',
payload: 'Learn Redux'
});
redux:Reducer
Personal understanding : receive action.type And the old state, Calculate new... Based on demand state
The essence : Pure function , Calculation State The process of , As long as it's the same input , Must get the same output
combineReducers
- Redux Provided , be used for Reducer The split
- function : Son Reducer Synthetic big Reducer, After the merger reducer Decide the whole state structure
redux:State
Store Object contains all data .
At present State, It can be done by store.getState() Get .const state = store.getState();
边栏推荐
- Rainbond结合NeuVector实践容器安全管理
- 如何选择导电滑环材料
- CockroachDB 分布式事务源码分析之 TxnCoordSender
- Explanation of characteristics of hydraulic slip ring
- 【暑期每日一題】洛穀 P1568 賽跑
- El cascade echo failed; El cascader does not echo
- Detailed explanation of distributed global unique ID solution
- Rust hello-word
- Worried about infringement? Must share copyrightless materials on the website. Don't worry about the lack of materials for video clips
- Application and principle of ThreadPoolExecutor thread pool
猜你喜欢
One click deployment of highly available emqx clusters in rainbow
Use of STM32 expansion board temperature sensor and temperature humidity sensor
Copier le matériel de conseils de bébé ne peut pas être vide, comment résoudre?
Causes of short circuit of conductive slip ring and Countermeasures
And search: the suspects (find the number of people related to the nth person)
Ebpf cilium practice (2) - underlying network observability
Redis数据库的部署及常用命令
[summer daily question] Luogu p5886 Hello, 2020!
El cascade echo failed; El cascader does not echo
Numeric amount plus comma; JS two methods of adding three digits and a comma to numbers; JS data formatting
随机推荐
More than one file was found with OS independent path ‘lib/armeabi-v7a/libyuv. so‘.
Solution: drag the Xib control to the code file, and an error setvalue:forundefined key:this class is not key value coding compliant for the key is reported
LeetCode1497-检查数组对是否可以被 k 整除-数组-哈希表-计数
Global and Chinese markets of Ethernet communication modules 2022-2028: Research Report on technology, participants, trends, market size and share
液压滑环的特点讲解
云原生存储解决方案Rook-Ceph与Rainbond结合的实践
Pico neo3 handle grabs objects
Sqlplus connects using the instance name
LevelDB源码分析之memtable
Tar command
Global and Chinese markets of gps/gnss receiver modules 2022-2028: Research Report on technology, participants, trends, market size and share
tar命令
Global and Chinese market of paper machine systems 2022-2028: Research Report on technology, participants, trends, market size and share
HCIP Day13
担心侵权?必备无版权素材网站分享,不用担心视频剪辑缺素材
[daily question in summer] letter delivery by p1629 postman in Luogu (to be continued...)
AcWing 886. Finding combinatorial number II (pretreatment factorial)
LeetCode316-去除重复字母-栈-贪心-字符串
了解 JVM 中几个相关问题 — JVM 内存布局、类加载机制、垃圾回收
el-cascader回显失败;el-cascader回显不出来