React-Redux:状态已更新但未复制

时间:2016-09-12 08:50:03

标签: javascript reactjs redux state reducers

在我的reducer中,我无法理解为什么我的状态返回更新但未复制。

const loginReducer = (state = {}, action) => {

    let newstate = JSON.parse(JSON.stringify(state))
    const { type, payload } = action

    switch(type) {
        case constant.LOGIN_SUCCESS:
            //
            newstate = { login: [{ user: payload.user, password: payload.password, logged: true }] }
            console.log(newstate.login)
            break;
        default:
            break;
    }

    return newstate

}

我错过了一件简单的事情,但我无法弄清楚

1 个答案:

答案 0 :(得分:0)

您似乎完全在此行中重新分配newstate

newstate = { login: [{ user: payload.user, password: payload.password, logged: true }] }

如果您想要保留state中的当前值,您还需要包含它们:

newstate = { ...newstate, login: [{ user: payload.user, password: payload.password, logged: true }] }

以上使用对象传播,您可能会或可能不会在您的babel配置中使用。您也可以使用Object.assign来实现相同的目标:

newstate = Object.assign(newstate, { login: [{ user: payload.user, password: payload.password, logged: true }] });