美文网首页
Redux学习

Redux学习

作者: 小话001 | 来源:发表于2023-02-02 11:38 被阅读0次

    Redux概念:一个帮助我们管理State的容器,是javaScript的状态容器,提供了可预测的状态管理;
    redux中的reducer概念:要求是一个纯函数(确定的输入,一定会有确定的输出;没有产生副作用)
    比如:slice(纯函数)、splice会对原来的数组修改,不是一个纯函数.
    所有React组件都必须像纯函数一样保护它们的props不被修改

    • 核心理念:Store
    • 核心理念:action

    所有的数据变化,必须通过派发(dispath)action来更新
    action:是一个普通的javascript对象,用来描述这次更新的type和content

    const aciont1 = { type:"INC_AGE", index:0 }
    const aciont2 = { type:"CHANGE_NAME", playload:{index:0,newName:"haha"} }
    
    • 核心理念:reducer
    1. 是一个纯函数
    2. 做的事情就是将传入的state和action结合起来生成一个新的state
    function reducer(state = initialState, action) {
      switch (action.type) {
        case "INC_AGE":
          return { ...state, counter: state.counter + action.num }
        case "CHANGE_NAME":
          return { ...state, counter: state.counter - action.num }
        default:
          return state
      }
    }
    export default reducer
    

    三大原则:

    1. 单一数据源

    • 整个应用程序的state被存储在一颗object tree中,并且这个object tree只存储在一个 store 中;
    • Redux并没有强制让我们不能创建多个Store,但是那样做并不利于数据的维护;
    • 单一的数据源可以让整个应用程序的state变得方便维护、追踪、修改;
      2.State是只读的
    • 唯一修改State的方法一定是触发action,不要试图在其他地方通过任何的方式来修改State:
    • 这样就确保了View或网络请求都不能直接修改state,它们只能通过action来描述自己想要如何修改state;
    • 这样可以保证所有的修改都被集中化处理,并且按照严格的顺序来执行,所以不需要担心race condition(竟态)的问题
      3.使用纯函数来执行修改
    • 通过reducer将 旧state和 actions联系在一起,并且返回一个新的State;
    • 随着应用程序的复杂度增加,我们可以将reducer拆分成多个小的reducers,分别操作不同state tree的一部分;
    • 但是所有的reducer都应该是纯函数,不能产生任何的副作用;
    基本用法参考

    store/actionCreators.js

    import * as actionTypes from "./constants"
    
    export const addNumberAction = (num) => ({
      type: actionTypes.ADD_NUMBER,
      num
    })
    
    export const subNumberAction = (num) => ({
      type: actionTypes.SUB_NUMBER,
      num
    })
    

    store/constants.js

    export const ADD_NUMBER = "add_number"
    export const SUB_NUMBER = "sub_number"
    

    store/reducer.js

    import * as actionTypes from "./constants"
    
    const initialState = {
      counter: 100
    }
    
    function reducer(state = initialState, action) {
      switch (action.type) {
        case actionTypes.ADD_NUMBER:
          return { ...state, counter: state.counter + action.num }
        case actionTypes.SUB_NUMBER:
          return { ...state, counter: state.counter - action.num }
        default:
          return state
      }
    }
    export default reducer
    

    store/index.js

    import { createStore } from "redux"
    import reducer from "./reducer"
    
    const store = createStore(reducer)
    
    export default store
    

    以上写法过期的后续会调整,目前只是基本的思路理解

    相关文章

      网友评论

          本文标题:Redux学习

          本文链接:https://www.haomeiwen.com/subject/hjvihdtx.html