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

边栏推荐
- [RootersCTF2019]babyWeb
- Receiving package install and uninstall events
- Rust hello-word
- AcWing 885. Find the combination number I (recursive preprocessing)
- 【暑期每日一題】洛穀 P1568 賽跑
- Implementation of distributed lock
- More than one file was found with OS independent path ‘lib/armeabi-v7a/libyuv.so‘.
- 如何选择导电滑环材料
- AcWing 886. Finding combinatorial number II (pretreatment factorial)
- Youqitong [vip] v3.7.2022.0106 official January 22 Edition
猜你喜欢

Copy baby prompt: material cannot be empty. How to solve it?

Use and principle of Park unpark

液压滑环的特点讲解

提高企业产品交付效率系列(1)—— 企业应用一键安装和升级

Intelligent operation and maintenance: visual management system based on BIM Technology

How to traverse massive data in redis

如何创建一个根据进度改变颜色的进度条

Tar command

在Rainbond中一键部署高可用 EMQX 集群

Use of STM32 expansion board temperature sensor and temperature humidity sensor
随机推荐
el-form表单新增表单项动态校验;el-form校验动态表单v-if不生效;
Unit testing with mongodb
Global and Chinese market of protection circuit modules 2022-2028: Research Report on technology, participants, trends, market size and share
使用 Nocalhost 开发 Rainbond 上的微服务应用
[data recovery in North Asia] a data recovery case of raid crash caused by hard disk drop during data synchronization of hot spare disk of RAID5 disk array
CockroachDB 分布式事务源码分析之 TxnCoordSender
[NLP Li Hongyi] notes
Leetcode316- remove duplicate letters - stack - greedy - string
AcWing 885. Find the combination number I (recursive preprocessing)
AcWing 889. 01 sequence satisfying the condition (Cartland number)
Print stream and system setout();
Leetcode522- longest special sequence ii- hash table - String - double pointer
Using nocalhost to develop microservice application on rainbow
Global and Chinese markets of Ethernet communication modules 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese market of 3D CAD 2022-2028: Research Report on technology, participants, trends, market size and share
Practice of combining rook CEPH and rainbow, a cloud native storage solution
One click deployment of highly available emqx clusters in rainbow
点赞的云函数
3D建模与处理软件简介 刘利刚 中国科技大学
Global and Chinese market of digital badge 2022-2028: Research Report on technology, participants, trends, market size and share