当前位置:网站首页>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 .........
边栏推荐
- 4. Data splitting of Flink real-time project
- 17_Redis_Redis发布订阅
- Equipped with Ti am62x processor, Feiling fet6254-c core board is launched!
- 18_Redis_Redis主从复制&&集群搭建
- 02. After containerization, you must face golang
- 08_ strand
- 19_Redis_宕机后手动配置主机
- 5. Practice: jctree implements the annotation processor at compile time
- Practice of compiling principle course -- implementing an interpreter or compiler of elementary function operation language
- 02.面向容器化后,必须面对golang
猜你喜欢
随机推荐
學習使用php實現公曆農曆轉換的方法代碼
03_ Linear table_ Linked list
终于搞懂了JS中的事件循环,同步/异步,微任务/宏任务,运行机制(附笔试题)
Engineer evaluation | rk3568 development board hands-on test
让您的HMI更具优势,FET-G2LD-C核心板是个好选择
Markdown tutorial
Yolov5 code reproduction and server operation
20_ Redis_ Sentinel mode
XML Configuration File
How to write sensor data into computer database
List set & UML diagram
14_ Redis_ Optimistic lock
XML配置文件
Download blender on Alibaba cloud image station
Application of CDN in game field
MySQL -- Index Optimization -- order by
TiDB数据迁移工具概览
LeetCode_ Sliding window_ Medium_ 395. Longest substring with at least k repeated characters
使用 TiUP 部署 TiDB 集群
Set set you don't know