当前位置:网站首页>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();

边栏推荐
- Distributed architecture system splitting principles, requirements and microservice splitting steps
- HCIP Day13
- Daily question -leetcode1175- permutation of prime numbers - Mathematics
- Variable binding and deconstruction for rudimentary rust
- Design and application of immutable classes
- 如何选择导电滑环材料
- Youqitong [vip] v3.7.2022.0106 official January 22 Edition
- Global and Chinese market of 3D CAD 2022-2028: Research Report on technology, participants, trends, market size and share
- One click deployment of highly available emqx clusters in rainbow
- CockroachDB 分布式事务源码分析之 TxnCoordSender
猜你喜欢

Distributed - summary list

Numeric amount plus comma; JS two methods of adding three digits and a comma to numbers; JS data formatting

导电滑环短路的原因以及应对措施

Application and principle of ThreadPoolExecutor thread pool

Leetcode316- remove duplicate letters - stack - greedy - string

Dynamic verification of new form items in El form; El form verifies that the dynamic form V-IF does not take effect;

One click deployment of highly available emqx clusters in rainbow

Rainbond结合NeuVector实践容器安全管理

Unity drags and modifies scene camera parameters under the editor

C WPF uses dockpanel to realize screenshot box
随机推荐
Global and Chinese market for instant messaging security and compliance solutions 2022-2028: Research Report on technology, participants, trends, market size and share
【暑期每日一題】洛穀 P1568 賽跑
Rainbow combines neuvector to practice container safety management
Dynamic verification of new form items in El form; El form verifies that the dynamic form V-IF does not take effect;
[daily question in summer] Luogu p1568 race
C# wpf 使用DockPanel实现截屏框
QT等待框制作
轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷
Fluentd is easy to use. Combined with the rainbow plug-in market, log collection is faster
实战:redux的基本使用
Explanation of characteristics of hydraulic slip ring
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
Receiving package install and uninstall events
Unity drags and modifies scene camera parameters under the editor
0xc000007b应用程序无法正常启动解决方案(亲测有效)
Application and principle of ThreadPoolExecutor thread pool
Global and Chinese markets of Ethernet communication modules 2022-2028: Research Report on technology, participants, trends, market size and share
Set集合详细讲解
JS random verification code
Global and Chinese market of paper machine systems 2022-2028: Research Report on technology, participants, trends, market size and share