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

边栏推荐
- Global and Chinese market of protection circuit modules 2022-2028: Research Report on technology, participants, trends, market size and share
- Go learning notes (5) basic types and declarations (4)
- FileOutPutStream
- [daily question in summer] letter delivery by p1629 postman in Luogu (to be continued...)
- Global and Chinese markets of InGaAs APD arrays 2022-2028: Research Report on technology, participants, trends, market size and share
- Day 05 - file operation function
- eBPF Cilium实战(2) - 底层网络可观测性
- Intelligent operation and maintenance: visual management system based on BIM Technology
- 智慧运维:基于 BIM 技术的可视化管理系统
- Usage and principle of synchronized
猜你喜欢

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

Tar command

Single page application

第05天-文件操作函数

Distributed transactions - Solutions

How to select conductive slip ring material

0xc000007b应用程序无法正常启动解决方案(亲测有效)
![[RootersCTF2019]babyWeb](/img/b4/aa8f8e107a9dacbace72d4717b1834.png)
[RootersCTF2019]babyWeb

Leetcode522- longest special sequence ii- hash table - String - double pointer

Use and principle of AQS related implementation classes
随机推荐
提高企业产品交付效率系列(1)—— 企业应用一键安装和升级
More than one file was found with OS independent path ‘lib/armeabi-v7a/libyuv.so‘.
Global and Chinese markets of superconductor 2022-2028: Research Report on technology, participants, trends, market size and share
[daily question in summer] Luogu p2026 find the analytic formula of primary function
How to meet the requirements of source code confidentiality and source code security management
AcWing 889. 01 sequence satisfying the condition (Cartland number)
每日一题-LeetCode1175-质数排列-数学
Sqlplus connects using the instance name
Is there any good website or software for learning programming? [introduction to programming]?
[daily question in summer] Luogu p1568 race
Youqitong [vip] v3.7.2022.0106 official January 22 Edition
Redis数据库的部署及常用命令
Global and Chinese markets for soft ferrite cores 2022-2028: Research Report on technology, participants, trends, market size and share
How to hide browser network IP address and modify IP internet access?
Global and Chinese market of protection circuit modules 2022-2028: Research Report on technology, participants, trends, market size and share
Leetcode522- longest special sequence ii- hash table - String - double pointer
轻松上手Fluentd,结合 Rainbond 插件市场,日志收集更快捷
云原生存储解决方案Rook-Ceph与Rainbond结合的实践
Data consistency between redis and database
Application of industrial conductive slip ring