当前位置:网站首页>Redux - detailed explanation
Redux - detailed explanation
2022-07-02 15:32:00 【Mr. fingertip dancer】
One . First time to know Redux
amount to vue Medium vuex
1.redux It is an independent and specialized 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
have a look Redux Working schematic diagram
If you want to do Add one The operation process is as follows :
It is worth noting that :Reducers Not only Processing status available , You can also initialize the state (undefinded)

Two , The core concept
Store
stay redux Inside , only one Store, The data that the whole application needs to manage is in this Store Inside . This Store We can't change it directly , We can only return a new Store To change it .redux Provides a createStore To create state
import { createStore } from 'redux'
const store = createStore(reducer)action
This action It refers to an operation initiated by the view layer , tell Store We need to change . For example, the user clicks the button , We are going to request the list , The data of the list will change . Every action There has to be one type attribute , This means action The name of , then There can be one more payload attribute , This attribute can take some parameters , Used as a Store change :
const action = {
type: 'ADD_ITEM',
payload: 'new item', // Optional attribute
} The above example defines a named ADD_ITEM Of Action, It also carries a payload Parameters of . Redux It can be used Action Creator Batch to generate some Action.
Reducer
Above we define a Action, however Action Will not automatically send out the change operation to Store, So here we need one called dispatch Things that are , It is specially used to send action, But also good , This dispatch We don't need to define and implement ourselves ,redux It has been written for us , stay redux Inside ,store.dispatch() yes View issue Action The only way .
store.dispatch({
type: 'ADD_ITEM',
payload: 'new item', // Optional attribute
}) When dispatch Launched a action after , Will arrive reducer, So this reducer What do you use it for ? seeing the name of a thing one thinks of its function , This reducer Is used to calculate the new store Of ,reducer Receive two parameters : Current state And received action, Then it is calculated , Will return a new state.( As we have said before , You can't change it directly state, You must return a new state To make changes .)
const reducer = function(prevState, action) {
...
return newState;
}; This reducer It's a pure function . Pure function means , For the same input , There will only be the same output , Does not affect external values , It will not be affected by external values . Pure function belongs to the concept of functional programming , If you want to know more about the concept of pure functions , Please have a look at here
You can see , We're creating store When , We are createStore There is a reducer Parameters , ad locum , We just want to , Every time store.dispatch Send a new action,redux Will automatically call reducer, Return to new state.
Here's an example
Implement a computing function


1. So let's create one Redux Folder , Create separate store.js and reducers.js file
store.js in
// introduce creacteStore, Dedicated to creating redux The core of store object
import { legacy_createStore as createStore } from "redux";
// Introduced as Count Component services reducer
import countRedux from './reducers'
const store=createStore(countRedux)
// Expose
export default storereducers.js In file
This code refers to the schematic diagram above
// Receive two parameters The state before preState, And action objects action
//const init=0
export default function countRedux(preState,action) {
// from action Object :type,data
console.log(preState,action);
const {type,data}=action
// According to what was passed in type Determine what to do
switch (type) {
// If the type is plus , Use the value before transmission +action The value in , Back out
case 'add1':
return preState+data
case 'add2':
return preState-data
default:
// Return initialization data
return 0
}
}stay count.js in
store.getState() obtain reducx Return value in
store.dispatch() towards redux Sent in The value before the first parameter The second parameter is action object
store.subscribe() When Redux When the state changes , Force update rendar, Let the page render
import React, { Component } from 'react';
// Introduce state
import store from './redux/store.js'
class count extends Component {
state={
}
// Called when a component is mounted
componentDidMount(){
// When Redux When the state changes , Force update rendar, Let the page render
store.subscribe(() => {
this.setState({})
})
}
// Add
add1=() => {
const {value}=this.select
store.dispatch({type:'add1',data:value*1})
}
add2=() => {
const {value}=this.select
//console.log(typeof value)//string
store.dispatch({type:'add2',data:value*1})
}
add3=() => {
const {value}=this.select
//console.log(typeof value)//string
const count=store.getState()
//string+number=string So we need to string turn number
if(count%2!==0) {
store.dispatch({type:'add1',data:value*1})
}else{
alert(' Does not meet the odd number requirement ')
}
}
add4=() => {
const {value}=this.select
//console.log(typeof value)//string
//string+number=string So we need to string turn number
setInterval(()=>{
store.dispatch({type:'add1',data:value*1})
},2000)
}
render() {
return (
<div>
{/* To obtain state */}
<h4>{store.getState()}</h4>
<select ref={(c)=>{this.select=c}}>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
<button onClick={this.add1}>+</button>
<button onClick={this.add2}>-</button>
<button onClick={this.add3}> The current sum is odd plus </button>
<button onClick={this.add4}> Asynchronous add </button>
</div>
);
}
}
export default count;The forced update in the life cycle hook in the above code can be optimized
stay index.js Set in the entry file

The above method is abbreviated , Now we're going to transform
Observe the schematic diagram , We ignored the one above action, Let's create action.js file
action.js
Here you can add and subtract
/**
* Specially for Count Component generation action object
*/
// Add Abbreviated mode of arrow function
export const ceactAdd1Action=data=>({type:'add1',data:data})
// Subtraction Normal mode
export function ceactAdd2Action(data){
return {type:'add2',data:data}
}stay count.js Modify in process
Import first
import {ceactAdd1Action,ceactAdd2Action} from './redux/action.js'Modify the code
The addition of odd numbers is omitted here , And asynchronous addition

3、 ... and . asynchronous action
1. What is asynchronous action?
With asynchrony action, There must be synchronization action. General situation We put the object (Object) The form is called synchronization action
function (function) The form is called asynchronous action , Our example above action What is passed in is an object , He is synchronized
for instance :
If you go to the canteen for dinner ,1. You wait 5min Say serve to the waiter ( This is how the above example implements asynchrony )
2. You tell the waiter to serve in five minutes ,( This is asynchronous action)
2. When to use ?
When you make it clear that you don't want to give the delayed task to your own components , I want to give it to you action when
3. How to use it? ?
Install middleware Configure in store in
yarn add redux-thunkstay store.js Middle configuration

stay count.js in
add4=() => {
const {value}=this.select
//console.log(typeof value)//string
//string+number=string So we need to string turn number
store.dispatch(ceactAsyncAdd1Action(value*1,500))
}stay action.js in
Returns a function
export const ceactAsyncAdd1Action=(data,time)=>{
// The return function is asynchronous action
return () => {
setTimeout(() => {
store.dispatch(ceactAdd1Action(data))
},time)
}
}Four .react-rudex

We will continue to add .........
边栏推荐
- 12_Redis_Bitmap_命令
- 基于RZ/G2L | OK-G2LD-C开发板存储读写速度与网络实测
- [solution] educational codeforces round 82
- Leetcode skimming -- incremental ternary subsequence 334 medium
- Equipped with Ti am62x processor, Feiling fet6254-c core board is launched!
- 怎样从微信返回的json字符串中截取某个key的值?
- 03_ Linear table_ Linked list
- Huffman tree: (1) input each character and its weight (2) construct Huffman tree (3) carry out Huffman coding (4) find hc[i], and get the Huffman coding of each character
- 面对“缺芯”挑战,飞凌如何为客户产能提供稳定强大的保障?
- How does the computer set up speakers to play microphone sound
猜你喜欢

03_ Linear table_ Linked list

Build your own semantic segmentation platform deeplabv3+

Download blender on Alibaba cloud image station

How to choose a third-party software testing organization for automated acceptance testing of mobile applications

vChain: Enabling Verifiable Boolean Range Queries over Blockchain Databases(sigmod‘2019)

05_ queue

03. Preliminary use of golang

让您的HMI更具优势,FET-G2LD-C核心板是个好选择

自定义异常

Let your HMI have more advantages. Fet-g2ld-c core board is a good choice
随机推荐
How to avoid 7 common problems in mobile and network availability testing
17_Redis_Redis发布订阅
Real estate market trend outlook in 2022
How to conduct TPC-C test on tidb
Application of CDN in game field
Download blender on Alibaba cloud image station
Summary of the first three passes of sqli Labs
Tidb data migration tool overview
12_Redis_Bitmap_命令
自定义异常
XML配置文件
Principles, language, compilation, interpretation
4. Jctree related knowledge learning
04_ Stack
数据分析常见的英文缩写(一)
Yolov5 code reproduction and server operation
基于RZ/G2L | OK-G2LD-C开发板存储读写速度与网络实测
Markdown tutorial
10_ Redis_ geospatial_ command
Pytorch 保存tensor到.mat文件
