如何在Redux存储中处理单个值?

时间:2018-10-19 14:49:27

标签: javascript reactjs redux immutability

假设我们拥有这家商店:

// initialState.js file
export default = {
  _token: 'a hashed long string from server',
  user: {
    key: value,
    ... many more
  }
  .. many more
}

这是令牌的还原器:

import * as types from '../actions/actionTypes'
import initialState from './initialState'

export default function tokenReducer(state = initialState._token, action) {
  switch(action.type) {
    case types.CHANGE_TOKEN:
        console.log(action.payload) //  a new hashed long string from server
        return action.payload // payload is a token string that comes from server
     default: 
       return state

  }
}

可以吗?

我的意思是,为了防止使用initialState.token或散布运算符返回整个状态,我只在减速器中使用了Object.assign部分存储,我只是更新了字符串(令牌)。 / p>

这是从存储中仅更改一个字符串值的正确方法,还是我应该返回整个状态并像下面一样使用Object.assign

import * as types from '../actions/actionTypes'
import initialState from './initialState'

export default function tokenReducer(state = initialState._token, action) {
  switch(action.type) {
    case types.CHANGE_TOKEN:
        console.log(action.payload) //  a new hashed long string from server
        return {
           ...state ,
           Object.assign({}, state, {_token: action.payload})
        }
     default: 
       return state

  }
}

0 个答案:

没有答案