当前位置:网站首页>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 store
reducers.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-thunk
stay 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 .........
边栏推荐
- 03.golang初步使用
- Learn the method code of using PHP to realize the conversion of Gregorian calendar and lunar calendar
- 怎样从微信返回的json字符串中截取某个key的值?
- How does the computer set up speakers to play microphone sound
- How to choose a third-party software testing organization for automated acceptance testing of mobile applications
- 如何用 Sysbench 测试 TiDB
- Mavn builds nexus private server
- Redux——详解
- 10_ Redis_ geospatial_ command
- Leetcode skimming -- verifying the preorder serialization of binary tree # 331 # medium
猜你喜欢
基于RZ/G2L | OK-G2LD-C开发板存储读写速度与网络实测
03_ Linear table_ Linked list
. Solution to the problem of Chinese garbled code when net core reads files
Evaluation of embedded rz/g2l processor core board and development board of Feiling
Steps for Navicat to create a new database
How to choose a third-party software testing organization for automated acceptance testing of mobile applications
03_線性錶_鏈錶
Tidb data migration tool overview
20_ Redis_ Sentinel mode
21_ Redis_ Analysis of redis cache penetration and avalanche
随机推荐
Kibana basic operation
Leetcode skimming - remove duplicate letters 316 medium
【网络安全】网络资产收集
12_Redis_Bitmap_命令
Bing.com网站
Solve the problem of frequent interruption of mobaxterm remote connection
做好抗“疫”之路的把关人——基于RK3568的红外热成像体温检测系统
如何用 Sysbench 测试 TiDB
04. Some thoughts on enterprise application construction after entering cloud native
Real estate market trend outlook in 2022
Tidb data migration scenario overview
Engineer evaluation | rk3568 development board hands-on test
21_ Redis_ Analysis of redis cache penetration and avalanche
Yolov5 code reproduction and server operation
How to test tidb with sysbench
Markdown tutorial
Application and practice of Jenkins pipeline
How to conduct TPC-C test on tidb
XML配置文件
MySQL -- Index Optimization -- order by