当前位置:网站首页>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.
边栏推荐
- Display terrain database on osgearth ball
- GIS实战应用案例100篇(七十八)-多规合一数据库设计及数据入库
- [rust notes] 13 iterator (Part 1)
- Location of package cache downloaded by unity packagemanager
- Campus lost and found platform based on SSM, source code, database script, project import and operation video tutorial, Thesis Writing Tutorial
- Unity interactive water ripple post-treatment
- Introduction to Base64 coding
- P1596 [USACO10OCT]Lake Counting S
- Vscode, idea, VIM development tool shortcut keys
- Pit & ADB wireless debugging of vivo real machine debugging
猜你喜欢
UE4 source code reading_ Bone model and animation system_ Animation compression
Collection interface
分配异常的servlet
Unity editor expansion - scrolling list
Unity4.3.1 engine source code compilation process
Advanced OSG collision detection
Introduction to hexadecimal coding
Simply start with the essence and principle of SOM neural network
请求参数的发送和接收
UE4 source code reading_ Bone model and animation system_ Animation process
随机推荐
Cesium service deployment, and import and display local 3dfiles data
Osgearth north arrow display
Servlet的生命周期
[rust notes] 07 structure
UE4 call DLL
jupyter远程服务器配置以及服务器开机自启
php-fpm软件的安装+openresty高速缓存搭建
【Rust 笔记】11-实用特型
Message queue for interprocess communication
Simply start with the essence and principle of SOM neural network
Gradle's method of dynamically modifying APK package name
100 GIS practical application cases (78) - Multi compliance database design and data warehousing
[rust notes] 05 error handling
Unity interactive water ripple post-treatment
Unity editor expansion - window, sub window, menu, right-click menu (context menu)
Unity multi open script
[redis] redis persistent RDB vs AOF (source code)
Mxone Pro adaptive 2.0 film and television template watermelon video theme apple cmsv10 template
Dealing with duplicate data in Excel with xlwings
Transmit pictures with Base64 encoding