当前位置:网站首页>Redux - learning notes
Redux - learning notes
2022-07-03 08:39:00 【Rain shallow listen to the wind sing】
List of articles
1redux Introduce
1.1 Learning documents
1 English document : https://redux.js.org/
2 Chinese document : http://www.redux.org.cn/
3 Github: https://github.com/reactjs/redux
1.2redux What is it?
1 redux It is a special tool for state management JS library ( No react Plug-in library ).
2 It can be used in react, angular, vue Etc , But it's basically the same as react In combination with .
3 effect : Centralized management react The state shared by multiple components in the application .
1.3 When do you need to use redux
1 The state of a component , Need to make other components available at any time ( share ).
2 One component needs to change the state of another component ( signal communication ).
3 General principles : You don't have to , If you don't have to work hard to use .

2react-redux

3redux Workflow

ActionCreator : Equivalent to a waiter
type: Add, subtract, multiply, divide, and so on
data: Data like numbers
dispatch: distribution , hold action Continue to send down .
store: Dispatcher
reducer: Initialization status 、 Processing status
Initialization is also a action, In this action Before preciousState The value is undefined


4redux Three core concepts
action
1 The object of action
2 contain 2 Attributes
◦ type: Identity properties , The value is a string , only , Necessary attribute
◦ data: Data attribute , Any value type , Optional attribute
3 Example :{ type: 'ADD_STUDENT',data:{name: 'tom',age:18} }
reducer
1 Used to initialize the State 、 Processing status .
2 When processing , According to the old state and action, Generate new state The pure function of .
store
1 take state、action、reducer Connected objects
2 How to get this object ?
a.1 import {createStore} from 'redux'
a.2 import reducer from './reducers'
a.3 const store = createStore(reducer)
3 The function of this object ?
a.1 getState(): obtain state
a.2 dispatch(action): distribution action, Trigger reducer call , Generate new state
a.3 subscribe(listener): Register to listen , When new state when , Automatically call
5 Summation cases - pure react edition
increment if odd If it is an odd number, add
Asynchronous add 
create-react-app redux-test
mport React, {
Component } from 'react'
export default class Count extends Component {
state = {
count:0}
// Add
increment = ()=>{
const {
value} = this.selectNumber
const {
count} = this.state
this.setState({
count:count+value*1})
}
// Subtraction
decrement = ()=>{
const {
value} = this.selectNumber
const {
count} = this.state
this.setState({
count:count-value*1})
}
// Odd plus
incrementIfOdd = ()=>{
const {
value} = this.selectNumber
const {
count} = this.state
if(count % 2 !== 0){
this.setState({
count:count+value*1})
}
}
// Asynchronous add
incrementAsync = ()=>{
const {
value} = this.selectNumber
const {
count} = this.state
setTimeout(()=>{
this.setState({
count:count+value*1})
},500)
}
render() {
return (
<div>
<h1> The current sum is :{
this.state.count}</h1>
<select ref={
c => this.selectNumber = c}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={
this.increment}>+</button>
<button onClick={
this.decrement}>-</button>
<button onClick={
this.incrementIfOdd}> The current sum is odd plus </button>
<button onClick={
this.incrementAsync}> Asynchronous add </button>
</div>
)
}
}
6 Summation cases Redux Lite version
First call prestate and action Value
The first time it's called , You can see preState and action

prestate yes undefined,action Is initialization , Followed by random characters , Fear and writing type repeat .
redux Status change will not change the interface by default


To monitor redux, State change call render

In this case, call render
It still doesn't work , Direct calls do not work
Nothing updated , This will call render, success .
But then every component calls , Very inconvenient , Can be in index Next, make changes . You can put the whole app Call again render
Yes dom Of diff Algorithm , Not all rearranged .
Writing order

1redux/store
/* This file is dedicated to exposing a store object , There is only one application store object */
// introduce createStore, Dedicated to creating redux At the core of store object
import {
createStore} from 'redux'
// Introduced as Count Component services reducer
import countReducer from './count_reducer'
// expose store
export default createStore(countReducer)
2redux/count_reducer
/* 1. The file is used to create a file for Count Component services reducer,reducer The essence of is a function 2.reducer The function takes two arguments , Respectively : The state before (preState), Action object (action) */
const initState = 0 // Initialization status
export default function countReducer(preState=initState,action){
// console.log(preState);
// from action Get in object :type、data
const {
type,data} = action
// according to type Decide how to process the data
switch (type) {
case 'increment': // If it's plus
return preState + data
case 'decrement': // If it's a decrease
return preState - data
default:
return preState
}
}
3components/count/index
import React, {
Component } from 'react'
// introduce store, Used to get redux Save state in
import store from '../../redux/store'
export default class Count extends Component {
state = {
carName:' Mercedes c63'}
/* componentDidMount(){ // testing redux The change of state in the process , Just change , Just call render store.subscribe(()=>{ this.setState({}) }) } */
// Add
increment = ()=>{
const {
value} = this.selectNumber
store.dispatch({
type:'increment',data:value*1})
}
// Subtraction
decrement = ()=>{
const {
value} = this.selectNumber
store.dispatch({
type:'decrement',data:value*1})
}
// Odd plus
incrementIfOdd = ()=>{
const {
value} = this.selectNumber
const count = store.getState()
if(count % 2 !== 0){
store.dispatch({
type:'increment',data:value*1})
}
}
// Asynchronous add
incrementAsync = ()=>{
const {
value} = this.selectNumber
setTimeout(()=>{
store.dispatch({
type:'increment',data:value*1})
},500)
}
render() {
return (
<div>
<h1> The current sum is :{
store.getState()}</h1>
<select ref={
c => this.selectNumber = c}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={
this.increment}>+</button>
<button onClick={
this.decrement}>-</button>
<button onClick={
this.incrementIfOdd}> The current sum is odd plus </button>
<button onClick={
this.incrementAsync}> Asynchronous add </button>
</div>
)
}
}
4 modify index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
ReactDOM.render(<App/>,document.getElementById('root'))
store.subscribe(()=>{
ReactDOM.render(<App/>,document.getElementById('root'))
})
5app.js No modification 
summary

7 Full version
The new file :
1.count_action.js Dedicated to creating action object
2.constant.js Place easily miswritten type value
Just two more files , The object should actioncreators To create
1 establish count_action.js
/* The document is dedicated to Count Component generation action object */
import {
INCREMENT,DECREMENT} from './constant'
export const createIncrementAction = data => ({
type:INCREMENT,data})
export const createDecrementAction = data => ({
type:DECREMENT,data})
here ({}) Returns the object ,{ {}} by undefined as a result of {} It is considered to be outside the function {}
file
1components/count/index
import React, {
Component } from 'react'
// introduce store, Used to get redux Save state in
import store from '../../redux/store'
// introduce actionCreator, Dedicated to creating action object
import {
createIncrementAction,createDecrementAction} from '../../redux/count_action'
export default class Count extends Component {
state = {
carName:' Mercedes c63'}
/* componentDidMount(){ // testing redux The change of state in the process , Just change , Just call render store.subscribe(()=>{ this.setState({}) }) } */
// Add
increment = ()=>{
const {
value} = this.selectNumber
store.dispatch(createIncrementAction(value*1))
}
// Subtraction
decrement = ()=>{
const {
value} = this.selectNumber
store.dispatch(createDecrementAction(value*1))
}
// Odd plus
incrementIfOdd = ()=>{
const {
value} = this.selectNumber
const count = store.getState()
if(count % 2 !== 0){
store.dispatch(createIncrementAction(value*1))
}
}
// Asynchronous add
incrementAsync = ()=>{
const {
value} = this.selectNumber
setTimeout(()=>{
store.dispatch(createIncrementAction(value*1))
},500)
}
render() {
return (
<div>
<h1> The current sum is :{
store.getState()}</h1>
<select ref={
c => this.selectNumber = c}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={
this.increment}>+</button>
<button onClick={
this.decrement}>-</button>
<button onClick={
this.incrementIfOdd}> The current sum is odd plus </button>
<button onClick={
this.incrementAsync}> Asynchronous add </button>
</div>
)
}
}
2redux/constant
/* This module is used to define action In the object type Constant value of type , There is only one purpose : Easy to manage while preventing programmers from writing wrong words */
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
3redux/count_actions
/* The document is dedicated to Count Component generation action object */
import {
INCREMENT,DECREMENT} from './constant'
export const createIncrementAction = data => ({
type:INCREMENT,data})
export const createDecrementAction = data => ({
type:DECREMENT,data})
4redux/count_reducer
/* 1. The file is used to create a file for Count Component services reducer,reducer The essence of is a function 2.reducer The function takes two arguments , Respectively : The state before (preState), Action object (action) */
import {
INCREMENT,DECREMENT} from './constant'
const initState = 0 // Initialization status
export default function countReducer(preState=initState,action){
// console.log(preState);
// from action Get in object :type、data
const {
type,data} = action
// according to type Decide how to process the data
switch (type) {
case INCREMENT: // If it's plus
return preState + data
case DECREMENT: // If it's a decrease
return preState - data
default:
return preState
}
}
5redux/store
/* This file is dedicated to exposing a store object , There is only one application store object */
// introduce createStore, Dedicated to creating redux At the core of store object
import {
createStore} from 'redux'
// Introduced as Count Component services reducer
import countReducer from './count_reducer'
// expose store
export default createStore(countReducer)
6app
import React, {
Component } from 'react'
import Count from './components/Count'
export default class App extends Component {
render() {
return (
<div>
<Count/>
</div>
)
}
}
7index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
ReactDOM.render(<App/>,document.getElementById('root'))
store.subscribe(()=>{
ReactDOM.render(<App/>,document.getElementById('root'))
})
8 asynchronous action
(1). clear : Delayed actions don't want to be handed over to the component itself , I want to give it to you action
(2). When you need asynchrony action: Want to manipulate the State , But specific data is returned by asynchronous tasks .
(3). Specific code :
1).yarn add redux-thunk, And configured in store in
2). establish action No longer returns normal objects , It's a function , Write asynchronous tasks in this function .
3). When an asynchronous task has a result , Distribute a synchronized action To actually manipulate data .
(4). remarks : asynchronous action It doesn't have to be written , You can wait for the results of asynchronous tasks before distributing synchronization action.
边栏推荐
- Un système de gestion de centre commercial pour la conception de cours de technologie d'application de base de données
- 梯度下降法求解BP神经网络的简单Demo
- [concurrent programming] working mechanism and type of thread pool
- Eating fruit
- Visual Studio (VS) shortcut keys
- Cesium for unreal quick start - simple scenario configuration
- Sequence of map implementation classes
- Development experience and experience
- Binary to decimal, decimal to binary
- 【Rust 笔记】12-闭包
猜你喜欢

XPath实现XML文档的查询
![P1596 [USACO10OCT]Lake Counting S](/img/a7/07a84c93ee476788d9443c0add808b.png)
P1596 [USACO10OCT]Lake Counting S
![[RPC] RPC remote procedure call](/img/dc/872204ea47fcff04cdb72e18a2a4ef.jpg)
[RPC] RPC remote procedure call
![[concurrent programming] consistency hash](/img/5e/3d0a52caa8ca489a6e6267274bbb39.jpg)
[concurrent programming] consistency hash

梯度下降法求解BP神经网络的简单Demo
![[concurrent programming] Table hopping and blocking queue](/img/b7/023991a00956e469af855e7a81e126.jpg)
[concurrent programming] Table hopping and blocking queue

Introduction to hexadecimal coding

MySQL 8

Message queue for interprocess communication

Kwai 20200412 recruitment
随机推荐
redis集群系列四
Encoding and decoding of golang URL
Monotonic stack -503 Next bigger Element II
Location of package cache downloaded by unity packagemanager
Solution détaillée de toutes les formules de fonction de transfert (fonction d'activation) du réseau neuronal MATLAB
Kwai 20200412 recruitment
[rust notes] 02 ownership
php-fpm软件的安装+openresty高速缓存搭建
Simple demo of solving BP neural network by gradient descent method
MySQL 8
Downward compatibility and upward compatibility
注解简化配置与启动时加载
UE4 call DLL
Find the intersection of line segments
二进制转十进制,十进制转二进制
Mall management system of database application technology course design
Monotonic stack -42 Connect rainwater
Intersectionpicker in osgearth
请求参数的发送和接收
Introduction to hexadecimal coding