0

React中,我们有一个最佳实践,即不直接修改状态,即突变……这在Redux中也很重要……

/* initial state */
export const usersStartState = { users: { isLoggedIn: false } }

export default function users(state = usersStartState, action) {
    switch (action.type) {
        case actionTypes.users.IS_LOGGED_IN:
            return Object.assign({}, state,
                state.users.isLoggedIn = true)
        case actionTypes.users.IS_LOGGED_OUT:
            return Object.assign({}, state,
                state.users.isLoggedIn = false)
        default:
            return state
    }
};

以上不起作用,但任何人都可以帮助我如何正确更新嵌套对象属性?

4

2 回答 2

1

看起来你既要改变状态又要返回一个新的状态对象。你通过说改变状态state.users.isLoggedIn = ..,然后通过做返回一个新的状态对象return Object.assign(...)

相反,也许只是做

case actionTypes.users.IS_LOGGED_OUT:
  return { ...state, users: { ...state.users, isLoggedIn: false }};

另一种方法是创建状态副本并对其进行修改

// Create new object so we don't mutate state
let newState = {...state, users: {...state.users}; 
// Remember to do this for each nested object or you 
// will still be referencing that piece of the original state
switch (action.type) {
  case actionTypes.users.IS_LOGGED_IN:
    newState.users.isLoggedIn = true; // Make your changes
    return newState; // Return new state
  case actionTypes.users.IS_LOGGED_OUT:
    newState.users.isLoggedIn = true;
    return newState;
  default:
    return state;
}
于 2019-12-19T17:50:39.733 回答
1

你可以这样做

return {...state, users:{...state.users, isLoggedIn : true}}
于 2019-12-19T17:47:07.050 回答