Redux detailed introduction

basic concepts:

1) In the core store in redux, the store contains state, a single data source, and the state can only come from the warehouse.

2) The state is read-only, you can only get the state, you cannot modify the state in the warehouse violently

3)store state reducer action

4)dispatch subscrbe getState

    创建仓库:
        <script src="./js/redux.js"></script> 相当于在页面中引入Redux。
        在Redux这个对象上,有一个api,叫createStore,调用它,就可以创建一个仓库。
    使用仓库:
        dispatch subscrbe getState

    action:
        本质就是一个JS对象,这个对象中需要有一个属性,叫type,用来描述一个动作。

    reducer:
        本质是一个函数,纯函数,根据不同的action和上一次的状态,返回一个新的状态
        function reducer(state=initState, action){
    
    
            switch(action.type){
    
    
                case "INCREMENT":
                    return {
    
     number:state.number+1 }
                case "DECREMENT":
                    return {
    
     number:state.number-1 }
                default:
                    return state
            }
        }

To learn redux, you need to stand from two perspectives:

1) How to create a warehouse (use crateStore, prepare reducer, prepare action, prepare initial state)

2) How to use the warehouse (3 api)

dispath: used to dispatch an action
getState: get the latest state (the state can only be obtained from the warehouse)
subscribe: once subscribed, when the state in the warehouse changes, the function you subscribed will be executed, in this function you You can do something you want to do.

Enable redux debugging (placed on the warehouse)

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__

Call composeEnhancers()

let store = Redux.createStore(reducer,composeEnhancers())

action 和 action creator

action: The
essence is an object, which is used to describe an action. There must be a type attribute in it.

let increment = {
    
     type : "INCREMENT" }
let decrement = {
    
     type : "DECREMENT" }

Action creator:
essentially a function, the return value of this function is an action.

function increment(payload){
    
    
   return {
    
     type:"INCREMENT",payload:payload }
}
function decrement(payload){
    
    
   return {
    
     type:"DECREMENT",payload:payload }
}

For the initialization state:
1) It can be specified when reudcer is declared
2) When the warehouse is created, the initialization state can also be specified

Use redux in scaffolding

Merge manager

import {
    
     combineReducers } from "redux"
import counter from "./counter"
import todos from "./todos"

// reducer就是把两个reducer合并成了一个reducer
let reducer = combineReducers({
    
    
     counter, 
    todos
})
export default reducer; // 导出合并后的reducer

Dispatch is called directly inside createStore

Guess you like

Origin blog.csdn.net/QZ9420/article/details/112307772