当前位置:网站首页>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.
边栏推荐
- Kwai 20200412 recruitment
- Cesium for unreal quick start - simple scenario configuration
- Image processing 8-cnn image classification
- Base64 and base64url
- Talking about: is the HashSet set ordered or disordered /hashset set unique, why can we store elements with the same content
- Unity Editor Extension - Outline
- [public key cryptography] ECC elliptic cryptosystem (implementing ElGamal encryption method)
- Unity editor expansion - scrolling list
- [concurrent programming] Table hopping and blocking queue
- Message pack in C deserializes array objects
猜你喜欢

Jupyter remote server configuration and server startup

OpenGL learning notes

Introduction to Base64 coding

Graphics_ Games101/202 learning notes

Unity Editor Extension - drag and drop

Introduction to hexadecimal coding

UE4 source code reading_ Mobile synchronization

Solution détaillée de toutes les formules de fonction de transfert (fonction d'activation) du réseau neuronal MATLAB

Simple demo of solving BP neural network by gradient descent method

Thymeleaf 404 reports an error: there was unexpected error (type=not found, status=404)
随机推荐
请求参数的发送和接收
Student educational administration management system of C # curriculum design
swagger文档配置
Dom4j遍历和更新XML
详解sizeof、strlen、指针和数组等组合题
[rust notes] 12 closure
【更新中】微信小程序学习笔记_3
Sequence of map implementation classes
Why can void * be a general pointer
Mysql容器化(1)Docker安装MySQL
Image processing 8-cnn image classification
注解简化配置与启动时加载
Kwai 20200412 recruitment
Development experience and experience
Clion toolchains are not configured configure disable profile problem solving
Eating fruit
XPath实现XML文档的查询
Ue5 opencv plug-in use
Advanced OSG collision detection
[concurrent programming] synchronization container, concurrent container, blocking queue, double ended queue and work secret