Detailed explanation of the basic usage process of Redux
learning documents
Chinese documentation: http://www.redux.org.cn/
English documentation: https://redux.js.org/
Github: https://github.com/reactjs/redux
First, what is redux
1 Introduction:
- redux is a
状态管理
JS library dedicated to doing things(不是react插件库)
. - It can be used in
react, angular, vue
projects such as基本与react配合使用
. - Role: Centralized management of react applications
多个组件共享的状态
.
2. Under what circumstances do you need to use redux
- The state of a component needs to be available to other components
随时拿到(共享)
. - A component needs to change the state of another component (
通信
). - General principle:
能不用就不用
, if not used比较吃力才考虑使用
.
3. Redux workflow
Two, the three core concepts of redux
1,action
- object of action
- Contains 2 attributes
type: identification attribute, value is string, unique, required attribute
data: data attribute, value type is arbitrary, optional attribute - Example: { type: 'ADD_STUDENT', data:{name: 'tom', age:18} }
2,reducer
- It is used for initialization state and processing state.
- During processing, a pure function that generates a new state based on the old state and action.
3,store
- The object that ties state, action, and reducer together
- How to get this object?
import {
createStore} from 'redux'
import reducer from './reducers'
const store = createStore(reducer)
- The function of this object?
getState(): get state
dispatch(action): distribute action, trigger reducer call, generate new state
subscribe(listener): register listener, when a new state is generated, it will be called automatically
Three, the core API of redux
1,createstore()
Function: Create a store object containing the specified reducer
2, store object
- Role: the core management object of the redux library
- It internally maintains:
state
reducer
- Core method:
getState()
dispatch(action)
subscribe(listener)
- Specific coding:
store.getState()
store.dispatch({type:‘INCREMENT’, number})
store.subscribe(render)
3,applyMiddleware()
Role: Redux-based middleware (plug-in library) on the application
4,combineReducers()
Role: Merge multiple reducer functions
Fourth, use redux to write applications
1. Install
npm install --save redux
2. Create a new file
Under the src path, create a new store file
3. Define the warehouse:
new src/store/index.js
// 定义仓库
// 引入configureStore 定义仓库
import {
configureStore } from "@reduxjs/toolkit";
// 导入counterSlice
import counter from "./counterSlice";
// 导出
export const store = configureStore({
// 数据处理
reducer: {
counter
}
});
4. How to create counter data and modify data:
New src/store/counterSlice.js
// 创建计数器切片slice
// 导入创建切片的函数
import {
createSlice } from "@reduxjs/toolkit";
// 定义初始化状态
const initialState = {
value: 0 };
// 创建切片
const counterSlice = createSlice({
// 切片名称
name: "counter",
// 初始化状态
initialState,
// 定义处理器
reducers: {
// 处理加法
increment: state => {
state.value += 1;
},
// 处理减法
decrement: state => {
state.value -= 1;
},
// 处理加法
addValue: (state, action) => {
state.value += action.payload;
}
}
});
// 导出动作
export const {
increment, decrement, addValue } = counterSlice.actions;
// 导出处理器
export default counterSlice.reducer;
// 导出异步操作动作
export const syncAddvalue = value => dispatch => {
setTimeout(() => {
dispatch(addValue(value));
}, 2000);
};
5. Use redux in components
src/views/ProductView.js file:
import {
increment,
decrement,
addValue,
syncAddvalue
} from "../store/counterSlice";
import {
useSelector, useDispatch } from "react-redux";
const ProductView = () => {
// 获取仓库数据
const count = useSelector(state => state.counter.value);
// 获取修改仓库数据的工具
const dispatch = useDispatch();
return (
<div>
<p>
仓库数据:{
count}
</p>
<button onClick={
() => dispatch(increment())}>+1</button>
<button onClick={
() => dispatch(decrement())}>-1</button>
<button onClick={
() => dispatch(addValue(5))}>+5</button>
<button onClick={
() => dispatch(syncAddvalue(10))}>两秒后+10</button>
</div>
);
};
export default ProductView;
Renderings:
Five, redux asynchronous programming
1. Understand:
- Redux cannot perform asynchronous processing by default.
- Sometimes the application needs to be in
redux中执行异步任务
(ajax, timer)
2. Use asynchronous middleware
npm install --save redux-thunk
Six, react-redux
1. understand
- A react plugin library
- Specifically designed to simplify the use of redux in react applications
2. react-Redux divides all components into two categories
- UI components
- It is only responsible for the rendering of the UI without any business logic
- Receive data through props (general data and functions)
- Does not use any Redux API
- Generally saved in the components folder
- container component
- Responsible for managing data and business logic, not responsible for UI presentation
- APIs using Redux
- Generally saved in the containers folder
3. Related APIs
- Provider: Let all components get state data
<Provider store={
store}>
<App />
</Provider>
- connect: Used to wrap UI components to generate container components
import {
connect } from 'react-redux'
connect(
mapStateToprops,
mapDispatchToProps
)(Counter)
- mapStateToprops: converts external data (that is, state objects) into label properties of UI components
const mapStateToprops = function (state) {
return {
value: state
}
}
- mapDispatchToProps: Convert the function of dispatching action to the label attribute of UI component
Seven, use the redux debugging tool
1. Install the chrome browser plug-in
2. Download the tool dependency package
npm install --save-dev redux-devtools-extension
Eight, pure functions and higher-order functions
1. Pure functions
- A special kind of function: As long as it is the same input (actual parameter), it must get the same output (return)
- The following constraints must be observed
- Do not overwrite parameter data
- Does not produce any side effects such as network requests, input and output devices
- Impurity methods such as Date.now() or Math.random() cannot be called
- The reducer function of redux must be a pure function
2. Higher-order functions
-
Understanding: a special class of functions
- Case 1: The parameter is a function
- Case 2: The return is a function
-
Common higher-order functions:
- Timer setting function
- Array's forEach()/map()/filter()/reduce()/find()/bind()
- promise
- The connect function in react-redux
-
Role: can achieve more dynamic and more scalable functions