当前位置:网站首页>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 .........
边栏推荐
- Download blender on Alibaba cloud image station
- 党史纪实主题公益数字文创产品正式上线
- JVM architecture, classloader, parental delegation mechanism
- Tidb environment and system configuration check
- NBA player analysis
- Principles, language, compilation, interpretation
- 02. After containerization, you must face golang
- List集合&UML图
- Tidb cross data center deployment topology
- Tidb data migration scenario overview
猜你喜欢

How does the computer set up speakers to play microphone sound

04_ 栈

2022 年辽宁省大学生数学建模A、B、C题(相关论文及模型程序代码网盘下载)

I made an istio workshop. This is the first introduction

Mavn builds nexus private server

飞凌嵌入式RZ/G2L处理器核心板及开发板上手评测

08_ strand

Facing the challenge of "lack of core", how can Feiling provide a stable and strong guarantee for customers' production capacity?

Storage read-write speed and network measurement based on rz/g2l | ok-g2ld-c development board

List set & UML diagram
随机推荐
03_線性錶_鏈錶
Leetcode skimming -- incremental ternary subsequence 334 medium
如何用 Sysbench 测试 TiDB
17_Redis_Redis发布订阅
Libcurl Lesson 13 static library introduces OpenSSL compilation dependency
How does the computer set up speakers to play microphone sound
Leetcode skimming -- count the number of numbers with different numbers 357 medium
SQL transaction
5. Practice: jctree implements the annotation processor at compile time
15_Redis_Redis.conf详解
哈夫曼树:(1)输入各字符及其权值(2)构造哈夫曼树(3)进行哈夫曼编码(4)查找HC[i],得到各字符的哈夫曼编码
MySQL -- Index Optimization -- order by
FPGA - 7系列 FPGA内部结构之Clocking -03- 时钟管理模块(CMT)
. Solution to the problem of Chinese garbled code when net core reads files
让您的HMI更具优势,FET-G2LD-C核心板是个好选择
Practical debugging skills
飞凌嵌入式RZ/G2L处理器核心板及开发板上手评测
面对“缺芯”挑战,飞凌如何为客户产能提供稳定强大的保障?
Set set you don't know
18_ Redis_ Redis master-slave replication & cluster building
