使用 createSlice 部分重置状态

时间:2021-01-26 12:56:49

标签: reactjs redux redux-toolkit

我有一个操作,它应该对某些状态属性进行部分重置。

在转向 redux-toolkit 之前,我已经使用以下代码实现了这一点:

initialState

const initialState = {
    username: null,
    dateOfBirth: null,
    homeTown: null,
    address: null,
    postCode: null,
    floor: null,
}

减速器

switch (action.type) {
    ...
    case USER_SET_HOME_TOWN:
        return {
            ...initialState,
            homeTown: action.payload
            username: state.userName,
            dateOfBirth: state.dateOfBirth,
        };
    ...
    default:
      return state;
}

USER_SET_HOME_TOWN 每次更改 homeTown 时都会被分派并维护用户名和 dateOfBirth,同时将其他所有内容返回到 initialState

现在使用 redux 工具包和 createSlice 我试图通过编写类似的东西来实现类似的行为:

createSlice - 不工作

const user = createSlice({
    name: 'user',
    ...
    reducers: {
        ...
        userSetHomeTown: {
            reducer: (state, action) => {
                state = { ...initialState };
                state.homeTown = action.payload;
                state.username = state.payload;
                state.dateOfBirth = state.dateOfBirth;
            },
        },
        ...
    },
});

这行不通,我想这是有道理的,因为 state = { ...initialState}; 重置了 statestate.username/dateOfBirth: state.username/dateOfBirth; 那时有点没用并且适得其反……或者只是错误.

将其更改为:

createSlice - 工作

const user = createSlice({
    name: 'user',
    ...
    reducers: {
        ...
        userSetHomeTown: {
            reducer: (state, action) => ({
                ...initialState,
                homeTown: action.payload,
                username: state.payload,
                dateOfBirth: state.dateOfBirth,
            }),
        },
        ...
    },
});

它确实有效,但我仍然想知道这是否是推荐的正确方法。

1 个答案:

答案 0 :(得分:2)

是的,没错。

请记住,Immer 的工作方式是改变现有状态对象 (state.someField = someValue),或者返回一个您自己不可变地构建的全新值。

仅仅做 state = initialState 都不是。它所做的只是将局部变量 state 指向不同的引用。

这里的另一个选项是 Object.assign(state, initialState),它会覆盖 state 中的字段,从而对其进行变异。