当前位置:网站首页>Redux - learning notes
Redux - learning notes
2022-07-03 08:39:00 【Rain shallow listen to the wind sing】
List of articles
1redux Introduce
1.1 Learning documents
1 English document : https://redux.js.org/
2 Chinese document : http://www.redux.org.cn/
3 Github: https://github.com/reactjs/redux
1.2redux What is it?
1 redux It is a special 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 .
1.3 When do you need to use redux
1 The state of a component , Need to make other components available at any time ( share ).
2 One component needs to change the state of another component ( signal communication ).
3 General principles : You don't have to , If you don't have to work hard to use .

2react-redux

3redux Workflow

ActionCreator : Equivalent to a waiter
type: Add, subtract, multiply, divide, and so on
data: Data like numbers
dispatch: distribution , hold action Continue to send down .
store: Dispatcher
reducer: Initialization status 、 Processing status
Initialization is also a action, In this action Before preciousState The value is undefined


4redux Three core concepts
action
1 The object of action
2 contain 2 Attributes
◦ type: Identity properties , The value is a string , only , Necessary attribute
◦ data: Data attribute , Any value type , Optional attribute
3 Example :{ type: 'ADD_STUDENT',data:{name: 'tom',age:18} }
reducer
1 Used to initialize the State 、 Processing status .
2 When processing , According to the old state and action, Generate new state The pure function of .
store
1 take state、action、reducer Connected objects
2 How to get this object ?
a.1 import {createStore} from 'redux'
a.2 import reducer from './reducers'
a.3 const store = createStore(reducer)
3 The function of this object ?
a.1 getState(): obtain state
a.2 dispatch(action): distribution action, Trigger reducer call , Generate new state
a.3 subscribe(listener): Register to listen , When new state when , Automatically call
5 Summation cases - pure react edition
increment if odd If it is an odd number, add
Asynchronous add 
create-react-app redux-test
mport React, {
Component } from 'react'
export default class Count extends Component {
state = {
count:0}
// Add
increment = ()=>{
const {
value} = this.selectNumber
const {
count} = this.state
this.setState({
count:count+value*1})
}
// Subtraction
decrement = ()=>{
const {
value} = this.selectNumber
const {
count} = this.state
this.setState({
count:count-value*1})
}
// Odd plus
incrementIfOdd = ()=>{
const {
value} = this.selectNumber
const {
count} = this.state
if(count % 2 !== 0){
this.setState({
count:count+value*1})
}
}
// Asynchronous add
incrementAsync = ()=>{
const {
value} = this.selectNumber
const {
count} = this.state
setTimeout(()=>{
this.setState({
count:count+value*1})
},500)
}
render() {
return (
<div>
<h1> The current sum is :{
this.state.count}</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>
)
}
}
6 Summation cases Redux Lite version
First call prestate and action Value
The first time it's called , You can see preState and action

prestate yes undefined,action Is initialization , Followed by random characters , Fear and writing type repeat .
redux Status change will not change the interface by default


To monitor redux, State change call render

In this case, call render
It still doesn't work , Direct calls do not work
Nothing updated , This will call render, success .
But then every component calls , Very inconvenient , Can be in index Next, make changes . You can put the whole app Call again render
Yes dom Of diff Algorithm , Not all rearranged .
Writing order

1redux/store
/* 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 {
createStore} from 'redux'
// Introduced as Count Component services reducer
import countReducer from './count_reducer'
// expose store
export default createStore(countReducer)
2redux/count_reducer
/* 1. The file is used to create a file for Count Component services reducer,reducer The essence of is a function 2.reducer The function takes two arguments , Respectively : The state before (preState), Action object (action) */
const initState = 0 // Initialization status
export default function countReducer(preState=initState,action){
// console.log(preState);
// 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 decrease
return preState - data
default:
return preState
}
}
3components/count/index
import React, {
Component } from 'react'
// introduce store, Used to get redux Save state in
import store from '../../redux/store'
export default class Count extends Component {
state = {
carName:' Mercedes c63'}
/* componentDidMount(){ // testing redux The change of state in the process , Just change , Just call render store.subscribe(()=>{ this.setState({}) }) } */
// Add
increment = ()=>{
const {
value} = this.selectNumber
store.dispatch({
type:'increment',data:value*1})
}
// Subtraction
decrement = ()=>{
const {
value} = this.selectNumber
store.dispatch({
type:'decrement',data:value*1})
}
// Odd plus
incrementIfOdd = ()=>{
const {
value} = this.selectNumber
const count = store.getState()
if(count % 2 !== 0){
store.dispatch({
type:'increment',data:value*1})
}
}
// Asynchronous add
incrementAsync = ()=>{
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>
)
}
}
4 modify index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
ReactDOM.render(<App/>,document.getElementById('root'))
store.subscribe(()=>{
ReactDOM.render(<App/>,document.getElementById('root'))
})
5app.js No modification 
summary

7 Full version
The new file :
1.count_action.js Dedicated to creating action object
2.constant.js Place easily miswritten type value
Just two more files , The object should actioncreators To create
1 establish count_action.js
/* The document is dedicated to Count Component generation action object */
import {
INCREMENT,DECREMENT} from './constant'
export const createIncrementAction = data => ({
type:INCREMENT,data})
export const createDecrementAction = data => ({
type:DECREMENT,data})
here ({}) Returns the object ,{ {}} by undefined as a result of {} It is considered to be outside the function {}
file
1components/count/index
import React, {
Component } from 'react'
// introduce store, Used to get redux Save state 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 {
state = {
carName:' Mercedes c63'}
/* componentDidMount(){ // testing redux The change of state in the process , Just change , Just call render store.subscribe(()=>{ this.setState({}) }) } */
// Add
increment = ()=>{
const {
value} = this.selectNumber
store.dispatch(createIncrementAction(value*1))
}
// Subtraction
decrement = ()=>{
const {
value} = this.selectNumber
store.dispatch(createDecrementAction(value*1))
}
// Odd plus
incrementIfOdd = ()=>{
const {
value} = this.selectNumber
const count = store.getState()
if(count % 2 !== 0){
store.dispatch(createIncrementAction(value*1))
}
}
// Asynchronous add
incrementAsync = ()=>{
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>
)
}
}
2redux/constant
/* This module is used to define action In the object type Constant value of type , There is only one purpose : Easy to manage while preventing programmers from writing wrong words */
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
3redux/count_actions
/* The document is dedicated to Count Component generation action object */
import {
INCREMENT,DECREMENT} from './constant'
export const createIncrementAction = data => ({
type:INCREMENT,data})
export const createDecrementAction = data => ({
type:DECREMENT,data})
4redux/count_reducer
/* 1. The file is used to create a file for Count Component services reducer,reducer The essence of is a function 2.reducer The function takes two arguments , Respectively : The state before (preState), Action object (action) */
import {
INCREMENT,DECREMENT} from './constant'
const initState = 0 // Initialization status
export default function countReducer(preState=initState,action){
// console.log(preState);
// 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 decrease
return preState - data
default:
return preState
}
}
5redux/store
/* 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 {
createStore} from 'redux'
// Introduced as Count Component services reducer
import countReducer from './count_reducer'
// expose store
export default createStore(countReducer)
6app
import React, {
Component } from 'react'
import Count from './components/Count'
export default class App extends Component {
render() {
return (
<div>
<Count/>
</div>
)
}
}
7index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
ReactDOM.render(<App/>,document.getElementById('root'))
store.subscribe(()=>{
ReactDOM.render(<App/>,document.getElementById('root'))
})
8 asynchronous action
(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 , But specific data is returned by asynchronous tasks .
(3). Specific code :
1).yarn add redux-thunk, And configured in store in
2). establish action No longer returns normal objects , It's a function , Write asynchronous tasks in this function .
3). 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 synchronization action.
边栏推荐
- Constraintlayout's constraintset dynamically modifies constraints
- Huawei interview summary during the epidemic
- jupyter远程服务器配置以及服务器开机自启
- 简易入手《SOM神经网络》的本质与原理
- 【更新中】微信小程序学习笔记_3
- 【Rust 笔记】10-操作符重载
- Redis的数据结构
- Sequence of map implementation classes
- Exe file running window embedding QT window
- Development experience and experience
猜你喜欢

Monotonic stack -503 Next bigger Element II

Simple demo of solving BP neural network by gradient descent method

了解小程序的笔记 2022/7/3

Binary to decimal, decimal to binary

Monotonic stack -84 The largest rectangle in the histogram

Collection interface
![P1596 [USACO10OCT]Lake Counting S](/img/a7/07a84c93ee476788d9443c0add808b.png)
P1596 [USACO10OCT]Lake Counting S

二进制转十进制,十进制转二进制

Monotonic stack -42 Connect rainwater

Creation of osgearth earth files to the earth ------ osgearth rendering engine series (1)
随机推荐
Base64 and base64url
【Rust 笔记】08-枚举与模式
Servlet的生命周期
Osgearth starry background
jupyter远程服务器配置以及服务器开机自启
Student educational administration management system of C # curriculum design
【K&R】中文第二版 个人题解 Chapter1
Detailed explanation of all transfer function (activation function) formulas of MATLAB neural network
Vscode, idea, VIM development tool shortcut keys
Development material set
Unity editor expansion - draw lines
C course design employee information management system
Final review of Database Principles
UE4 source code reading_ Bone model and animation system_ Animation compression
Simply start with the essence and principle of SOM neural network
[updating] wechat applet learning notes_ three
Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)
Binary to decimal, decimal to binary
Find the intersection of line segments
Graphics_ Learnopongl learning notes