当前位置:网站首页>Redux summation case explanation version tutorial
Redux summation case explanation version tutorial
2022-07-23 19:49:00 【Crayon rudimentology code】
List of articles
Then at the end of the last article Use native react Version realizes the summation case
Next, we will introduce the application in three versions redux The process of realizing the sum case .
Interested friends, let's have a look ~

Use redux Write applications
Case needs
Summation cases :
There are five buttons , Drop down button to select addend , Click the plus or minus button , Operate the current sum number with the number selected from the drop-down , Get the current sum ,“ The current sum is odd ” Button means to add when the current sum is an odd number ,“ Asynchronous add ” The button indicates waiting 0.5s And then add
effect :

redux Simplified version writing ( Don't use action relevant API)
install redux:
npm add redux
According to the schematic diagram , We need to write store Objects and reducer The two core concepts of function .
src=> redux Folder => store.js:
/* 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 {
legacy_createStore as createStore } from 'redux';
// Introduced as Count Component services reducer
import countReducer from './count_reducer'
// expose store
export default createStore(countReducer)
src=> redux Folder => count_reducer.js: Initialization status And processing status
/* 1. This file is used to create a file called Count Component services reducer,reducer The essence of is a function 2.reducer The function will receive two parameters , Respectively : The state before (preState), Action object (action) */
// initialization state
const initState = 0
// preState = initState :es6 grammar , Give formal parameter prevState Initial value of Fu
export default function countReducer(preState = initState, action) {
// 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 minus
return preState - data
default:
return preState
}
}
Finished the code of the above two core concepts , And then back to Count Component modification code , Because the state in the component is handed over to redux management , So the component itself state There is no need to store count The value of .
How to show the initial value ?
Because the status has been handed over to redux management ,redux To store management , so call store object .
First introduced store:
import store from '../../redux/store'
Use one getState() Method to get the initial value state :
<h1> The current sum is :{
store.getState()}</h1>
How to achieve the addition effect ?
Because the state of the component itself does not count The value of , So it can't be used this.setState() Method to update the status .
We want to inform redux Plus getting what users click value value , Use store On the body dispatch() Method , Pass in a action object ,type by increment,data by value*1.
store.dispatch({
type: 'increment', data: value * 1 })
But the problem is ! The page did not achieve the desired effect , Click the Add button , There is no change .
So we can print , Every time you click the Add button , Judge preState There is no growth .

Print the results :

It can be seen from the printed results that , Every time you click the plus sign ,preState The value of is increasing , But the page remains the same , It indicates that the change of state is not rendered on the page .redux Just maintain the management status , After changing the status, the page will not be updated by default .
So we need to monitor redux State in , If redux The state in has changed , We call it ourselves render(), Update page .
How to monitor redux Change of state ?
When the component is attached to the page , On monitoring redux Change of state , As long as it changes , Just call render().
Use store On the body subscribe() Method : This method receives a callback function , as long as reudx Any state saved in changes , Call the callback . Call in the callback function this.setState({}), Just call , The updated page will be re rendered .
componentDidMount() {
// testing redux The change of state in the process , Just change , Just call render
store.subscribe(() => {
// as long as reudx Any state saved in changes , Call the callback
// console.log('@')
this.setState({
})
})
}
Count Components => index.jsx:
import React, {
Component } from 'react'
// introduce store, Used to get redux Status saved in
import store from '../../redux/store'
export default class Count extends Component {
componentDidMount() {
// testing redux The change of state in the process , Just change , Just call render
store.subscribe(() => {
// as long as reudx Any state saved in changes , Call the callback
// console.log('@')
this.setState({
})
})
}
// Add
increment = () => {
// Get user input
const {
value } = this.selectNumber
store.dispatch({
type: 'increment', data: value * 1 })
}
// Subtraction
decrement = () => {
// Get user input
const {
value } = this.selectNumber
store.dispatch({
type: 'decrement', data: value * 1 })
}
// Odd plus
incrementIfOdd = () => {
// Get user input
const {
value } = this.selectNumber
// Read the original status value
const count = store.getState()
if (count % 2 !== 0) {
store.dispatch({
type: 'increment', data: value * 1 })
}
}
// Asynchronous add
incrementAsync = () => {
// Get user input
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>
)
}
}
Sum up the cases _redux Lite version :
1️⃣ Remove Count The state of the component itself
2️⃣ src Set up under the :
-src
-redux
-store.js
-count_reducer.js
3️⃣
store.js:1). introduce redux Medium createStore function , Create a store
2).createStore When calling, pass in a reducer
3). Remember to expose store object
4️⃣
count_reducer.js:1).reducer The essence is A function , receive :preState,action, return : State after processing
2).reducer It does two things : Initialization status , Processing status
3).reducer When called for the first time , yes store Automatic triggering Of , Delivered preState yes undefined, Delivered action yes :{type:‘@@REDUX/INIT’}
5️⃣ stay index.js In the process of monitoring store Change of state in , Once it changes, re render
remarks :redux Only responsible for managing state , As for the state change driving the display of the page , It's up to us to write .
redux The complete version is written
In the compact version ,action The object is manually passed in by ourselves , Next, we'll implement redux It's automatically created for us action object .
stay redux Create under folder count_action.js file , This document is dedicated to by Count Component generation action Action object .
redux=> count_action.js:
// Expose separately
export const createIncrementAction = (data) => {
return {
type: 'increment', data: data }
}
export const createIDecrementAction = (data) => {
return {
type: 'Decrement', data: data }
}
stay Count Component Introduction count_action.js Functions exposed separately in the file :
// introduce actionCreator, Dedicated to creating action object
import {
createIncrementAction, createDecrementAction } from '../../redux/count_action'
Call function , Automatic generation action object :
// Add
increment = () => {
// Get user input
const {
value } = this.selectNumber
store.dispatch(createIncrementAction(value * 1))
}
And so on , Manually created in all methods action Object is changed to be automatically generated using a function action object .
Count Components => index.jsx:
import React, {
Component } from 'react'
// introduce store, Used to get redux Status saved 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 {
componentDidMount() {
// testing redux The change of state in the process , Just change , Just call render
store.subscribe(() => {
// as long as reudx Any state saved in changes , Call the callback
// console.log('@')
this.setState({
})
})
}
// Add
increment = () => {
// Get user input
const {
value } = this.selectNumber
store.dispatch(createIncrementAction(value * 1))
}
// Subtraction
decrement = () => {
// Get user input
const {
value } = this.selectNumber
store.dispatch(createDecrementAction(value * 1))
}
// Odd plus
incrementIfOdd = () => {
// Get user input
const {
value } = this.selectNumber
// Read the original status value
const count = store.getState()
if (count % 2 !== 0) {
store.dispatch(createIncrementAction(value * 1))
}
}
// Asynchronous add
incrementAsync = () => {
// Get user input
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>
)
}
}
We can also create a constant.js file , Used for definition action In the object type Type of Constant values , Originally written type The type is string , Not conducive to maintenance , In case of misspelling , No hints , So there is only one purpose : Easy to manage while preventing programmers from writing wrong words .
redux=> constant.js:
// Expose separately
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
redux=> count_action.js:
import {
INCREMENT, DECREMENT } from './constant'
// Expose separately
export const createIncrementAction = (data) => {
return {
type: INCREMENT, data: data }
}
export const createDecrementAction = (data) => {
return {
type: DECREMENT, data: data }
}
redux=> count_reducer.js:
import {
INCREMENT, DECREMENT } from './constant'
// initialization state
const initState = 0
// preState = initState :es6 grammar , Give formal parameter prevState Initial value of Fu
export default function countReducer(preState = initState, action) {
console.log(preState, action)
// 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 minus
return preState - data
default:
return preState
}
}
Sum up the cases _redux Full version :
The new file :
1️⃣ count_action.js Dedicated to establish action object
2️⃣ constant.js Place the wrong ones due to careless coding action Medium type value
redux asynchronous action edition
action Not only is Object Type of General object ( Sync action), Or a function Function value ( asynchronous action).
In the above case , When we implement the operation of adding buttons asynchronously , We are in Count A timer is written directly in the component ,5s Automatic addition after ,action yes Object General object of type , This is a Sync action edition .( It's like a guest eating in a restaurant , guest (React component) etc. 5s after , Call the waiter (action creator) Order )
// Asynchronous add
incrementAsync = () => {
// Get user input
const {
value } = this.selectNumber
setTimeout(() => {
store.dispatch(createIncrementAction(value * 1, 500))
}, 500)
}
// Sync action, Is refers to action The value of is Object General object of type
export const createIncrementAction = (data) => {
return {
type: INCREMENT, data: data }
}
however , I don't want to use timers in components , Directly in the function , Pass a 5s Parameters of , tell action etc. 5s Then add , there action It's a function Function value , This is a asynchronous action edition .( It's like a guest eating in a restaurant , guest (React component) Tell the waiter (action creator)5s Order later )
// Asynchronous add
incrementAsync = () => {
// Get user input
const {
value } = this.selectNumber
// setTimeout(() => {
store.dispatch(createIncrementAsyncAction(value * 1, 500))
// }, 500)
}
It is written in the component createIncrementAsyncAction() function , But the function has not been defined , So we need to count_action.js This function is defined in the file .
import store from './store'
// asynchronous action, Is refers to action The value of is a function , asynchronous action Synchronization is usually called in action
export const createIncrementAsyncAction = (data, time) => {
return () => {
setTimeout(() => {
store.dispatch(createIncrementAction(data))
}, time)
}
}
however , This is for store Is a function The value of the function type ,store Cannot handle value of function type , Will report a mistake , need Use a middleware , Give Way store Execute asynchronous tasks in this function .
Install middleware redux-thunk:
npm add redux-thunk
stay store.js Middleware is introduced into the file redux-thunk:
// introduce redux-thunk, Used to support asynchronous tasks
import thunk from 'redux-thunk'
We also need to introduce an implementation middleware applyMiddleware:
import {
applyMiddleware } from 'redux';
// Where to execute
export default createStore(countReducer, applyMiddleware(thunk))
stay createStore when , take applyMiddleware Pass in as the second parameter ,applyMiddleware Itself is a function , Execution middleware , So you have to pass in thunk.
Sum up the cases _redux asynchronous action edition :
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 , however Specific data is returned by asynchronous tasks .
3️⃣ Specific code :
- npm add redux-thunk, And configured in store in
- establish action No longer returns normal objects , It is A function , The Write asynchronous task in function
- 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 synchronous tasks action
Today's sharing is here \textcolor{red}{ Today's sharing is here } Today's sharing is here
Originality is not easy. , I also hope you guys can support \textcolor{blue}{ Originality is not easy. , I also hope you guys can support } Originality is not easy. , I also hope you guys can support
give the thumbs-up , Your recognition is the driving force of my creation ! \textcolor{green}{ give the thumbs-up , Your recognition is the driving force of my creation !} give the thumbs-up , Your recognition is the driving force of my creation !
️ Collection , Your favor is the direction of my efforts ! \textcolor{green}{ Collection , Your favor is the direction of my efforts !} Collection , Your favor is the direction of my efforts !
️ Comment on , Your opinion is the wealth of my progress ! \textcolor{green}{ Comment on , Your opinion is the wealth of my progress !} Comment on , Your opinion is the wealth of my progress !
边栏推荐
- Powercli management VMware vCenter batch deployment export import
- 固态硬盘的工作原理揭秘
- As a background developer, you must know two kinds of filters
- 【leetcode天梯】链表 · 206 反转链表
- web安全入门-ssh测试与防御
- H7-TOOL串口脱机烧录操作说明,支持TTL串口,RS232和RS485(2022-06-30)
- Brief analysis of compiling principle of.Net CLR R2R
- R language uses dwilcox function to generate Wilcoxon rank sum statistical distribution density function data, and uses plot function to visualize Wilcoxon rank sum statistical distribution density fu
- Codeforces round 809 (Div. 2) [VP record]
- Boundschecker usage "recommended collection"
猜你喜欢
随机推荐
H7-TOOL串口脱机烧录操作说明,支持TTL串口,RS232和RS485(2022-06-30)
Construction deployment scheme of GPS Beidou clock server (NTP network clock system)
Using FRP to achieve intranet penetration
什么是弱网测试?为什么要进行弱网测试?怎么进行弱网测试?「建议收藏」
PowerCLi 管理VMware vCenter 批量部署导出导入
Canvas draw text and clear draw
socat 使用「建议收藏」
H7-TOOL的CANFD/CAN接口脱机烧写操作说明, 已经更新(2022-07-12)
华为云HCS解决方案笔记HUAWEI CLOUD Stack【面试篇】
USB3.0:VL817Q7-C0的LAYOUT指南
入门数据库Days3
When does MySQL use table locks and row locks?
【leetcode天梯】链表 · 022 链表中倒数第k个节点
小熊拍学习之LED灯的点亮
【luogu P6656】【LOJ 173】【模板】Runs(字符串)(Lyndon 串)
三维点云课程(七)——特征点描述
FormatDateTime的用法
White paper on adaptive robot interaction
树莓派3b串口登录前准备工作
paddle实现,多维时序数据增强 ,mixup(利用beta分布制作连续随机数)









