reducer 中state处理方式

2020-05-09  本文已影响0人  lovelydong
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
      }
}
上一篇下一篇

猜你喜欢

热点阅读