美文网首页
reducer 中state处理方式

reducer 中state处理方式

作者: lovelydong | 来源:发表于2020-05-09 17:22 被阅读0次
    1. 官方实例中Object.assign方法,但需要将visibilityFilter中未更新的对象用原state的中的对象进行手动赋值
    function todoApp(state = initialState, action) {
      switch (action.type) {
        case SET_VISIBILITY_FILTER:
          return Object.assign({}, state, {
            visibilityFilter: {
              state.visibilityFilter.a,
              b:{
                d:action.filter
              }
            }
          })
          default:
            return state
      }
    }
    
    2. 采用对象展开运算符
    function todoApp(state = initialState, action) {
      switch (action.type) {
        case SET_VISIBILITY_FILTER:
          return {
            ...state, 
            visibilityFilter:{
              ...state.visibilityFilter, 
              b:{
                ...state.visibilityFilter.b,
                d:action.filter
              }
            }
          }
          default:
            return state
      }
    }  
    
    3. 将state进行深度对象克隆后,再进行更新
    import cloneDeep from 'lodash/cloneDeep'
    
    function todoApp(state = initialState, action) {
      switch (action.type) {
        case SET_VISIBILITY_FILTER:
          const newState = cloneDeep(state)
    //const newstate=JSON.parse(JSON.stringify(state)); 另一个方式
          newState.visibilityFilter.b.d = action.filter
          return newState
        default:
          return state
      }
    }
    
    
    4. 采用官方提供的Immutability Helper工具中update()方法进行数据更新
    import update from 'react/lib/update'
    
    function todoApp(state = initialState, action) {
      switch (action.type) {
        case SET_VISIBILITY_FILTER:
          return update(state, {
            visibilityFilter:{
              d:{$set: action.filter}
            }
          })
        default:
          return state
      }
    }
    
    

    demo

    
    export default (state = defaultState,action)=>{
      
        switch (action.type) {
            case 'changeInput':
            //   return Object.assign({}, state, {
            //     inputValue:action.value
            //   })
             return {
                 ...state, 
                 inputValue:action.value
                 
                }
          
              default:
                return state
          }
    }
    

    相关文章

      网友评论

          本文标题:reducer 中state处理方式

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