在不改变状态的情况下使对象变空?

时间:2017-09-07 07:25:54

标签: reactjs redux

我正在使用react和redux,如何将对象重新设置回{}

export default function checkInReducer(state = initialState.user, action) {
    switch (action.type) {
        case types.GET_USER_SUCCESS:
            return Object.assign({}, state, {
                ...action.user
              });

        case types.RESET_CHECKIN:
            //what should I do here? simply return {} ?

        default:
              return state; 
    }
}

2 个答案:

答案 0 :(得分:0)

在您的Reducer中,您已将默认状态设置为initialState.user

checkInReducer(state = initialState.user, action) {

因此,不应直接设置/返回{},而应以这种方式返回首字母状态。

case types.RESET_CHECKIN:
return initialState.user || {} //if initialState.user  is undefined then return {}

答案 1 :(得分:0)

正如您所说,initialState.user空对象

export default function checkInReducer(state = initialState.user, action) {
switch (action.type) {
    case types.GET_USER_SUCCESS:
        return Object.assign({}, state, {
            ...action.user
          });

    case types.RESET_CHECKIN:
        return initialState.user 

    default:
          return state; 
}
}