当前位置:网站首页>Redux quick start
Redux quick start
2022-07-29 04:24:00 【Tianluofeng】
List of articles
Here is just the simplest way to use
Prerequisite knowledge

- store: There is only one application store,redux Provide createStore Method to create store
- state: yes store Data in , Is read-only , Can pass :store.getState() obtain , The modification method is trigger action
- action: Used to tell redux You need to change state,action The resulting object must contain type attribute , indicate action name
- dispatch: Is used to action Pass to reducer, yes view communicate store The only way ! Generally in view On the call dispacth, Pass a ation In the past
- reducer: receive action and state, According to action Handle state, And return to a new state, It has to be a pure function ( As long as it's the same input , Must get the same output )
- subscribe: For monitoring state And execute the callback function .store.subscribe(callback) Method returns a function , Call this function to disable listening , Just put View The update function of ( about React project , It's the component render Method or setState Method ) Put in listen, It will come true View Automatic rendering of .
Practice process
Generally speaking , If it's a synchronization request :
- Definition action
function addAge(id) {
return {
type: 'ADD_AGE',
id
}
}
- Definition reducer
const defaultState = {
name:"",age:0,id:""};
const reducer = (state = defaultState, action) => {
switch (action.type) {
case 'ADD_AGE':
// Omit processing logic
return {
...state,age:state.age+1};
default:
return state;
}
};
- establish store
import {
createStore } from 'redux';
const store = createStore(reducer);
- Page call
export default function App() {
const [state, setState] = useState({
});
useEffect(() => {
return Store.subscribe(() => {
setState(Store.getState()); // When subscribing , Registered a callback function , Every time the status is updated , This function will be called automatically
});
}, []);
function click() {
Store.dispatch(addAge("123"));
}
return(<>{
state}</>)
}
stay In the asynchronous case , Middleware is required , because :dispatch One action after , arrive reducer Before , Do some extra work , It needs to be used middleware. You can use Redux middleware To log 、 Create crash report 、 Call asynchronous interface or route, etc .
- Introduce middleware redux-thunk
import {
applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
// The middleware can make the original dispatch The received object becomes a function
// If it is an object, it will be normally received and sent to reducer, If it is a function, execute the function
const store = createStore(
reducers,
applyMiddleware(thunk)
);
- Write services.js, Definition API structure , Such as
export function getInfo(name){
return Axios.get('/test?name='+name);
}
- Define an asynchronous action, Returns a function , Participation is dispatch
const GET_INFO = ' pick up information ';
const getInfo = async name => dispatch =>{
// Logical ellipsis
getInfo(name).then(res=>dispatch({
type: 'GET_INFO ',
info:res
})
}
Everything else is the same
react-redux
Only in view The layers are different : Two new functions are added , Meaning is literally
- mapStateToProps
- mapDispatchToProps
Add a higher-order function :connect(mapStateToProps,mapDispatchToProps), Returns a function , Pass the component into the returned function to get the wrapped component !
Usage method :
import React from "react";
import {
connect } from "react-redux";
import {
Action01, Action02 } from "../../actions/Demo01";
function Demo_01(props) {
return (
<div>
demo_01
<div></div>
<button onClick={
() => props.action01("bt1")}>action01</button>
<button onClick={
() => props.action02("bt2")}>action02</button>
<p>{
props.msg}</p>
<p>{
props.value}</p>
</div>
);
}
export default connect(
function mapStateToProps(state) {
return {
msg: state.Demo01.msg,
value: state.Demo01.value
};
},
function mapDispatchToProps(dispatch) {
return {
action01: (msg) => dispatch(Action01(msg)),
action02: (value) => dispatch(Action02(value))
};
}
)(Demo_01);
Merge multiple reducer And provide the initial state of the application
Use combineReducers Middleware to merge multiple reducer, Used to divide States
import {
createStore, combineReducers, applyMiddleware } from "redux";
import ReduxThunk from "redux-thunk";
import Demo01Reducer from "../reducers/Demo01";
import Demo02Reducer from "../reducers/Demo02";
import Demo01State from "../state/Demo01";
import Demo02State from "../state/Demo02";
const allReducers = combineReducers({
Demo01: Demo01Reducer
Demo02: Demo02Reducer
});
export default createStore(
allReducers,
{
Demo01: Demo01State,
Demo02: Demo02State
},
applyMiddleware(ReduxThunk)
);
边栏推荐
- LeetCode_ Stack topics
- Multi card training in pytorch
- Whole house WiFi solution: mesh router networking and ac+ap
- 顺序表和链表
- Why is it necessary to scale the attention before softmax (why divide by the square root of d_k)
- Wechat applet parameter transfer
- leetcode 686.重复叠加字符串 KMP方法(C语言实现)
- String, array, generalized table (detailed)
- Leftmost prefix principle of index
- Visio draw grid
猜你喜欢

不会就坚持68天吧 狒狒吃香蕉

Compilation and linking

Svg -- loading animation

Implementation of jump connection of RESNET (pytorch)

恒星科通邀您“湘”约第24届中国高速公路信息化大会暨技术产品展示会

It won't last for 65 days. It only appears once

15.federation

不会就坚持67天吧 平方根

Common components of solder pad (2021.4.6)

Won't you just stick to 69 days? Merge range
随机推荐
14.haproxy+keepalived负载均衡和高可用
Why is it necessary to scale the attention before softmax (why divide by the square root of d_k)
不会就坚持58天吧 实现前缀树
不会就坚持71天吧 链表排序
es6和commonjs对导入导出的值修改是否影响原模块
HC06 HC05 BT
WebRTC实现简单音视频通话功能
kotlin的List,Map,Set等集合类不指定类型
Model tuning, training model trick
Update learning materials daily
15.federation
Database SQL statement realizes function query of data decomposition
C语言:浅谈各种复杂的声明
On quotation
10.回退消息
SVG--loading动画
Class starts! See how smardaten decomposes complex business scenarios
6.pytest生成allure报告
C language: enumerating knowledge points summary
Integration of Nan causes in pytorch training model