我如何清除状态的一部分

how do I clear a slice of the state

有没有一种优雅的方法来清除状态的切片?我的状态下有 7 个数据片段,我想在擦除其余数据的同时保持其中一个处于活动状态。我是否需要 运行 通过我的每个减速器并手动擦除每个减速器中的切片,还是有其他方法?

提前致谢...

您可以执行以下操作:

const resetState = () => ({
  type: 'RESET_STATE'
})

const appReducer = combineReducers({
  /* your app’s top-level reducers */
})

const rootReducer = (state, action) => {
  if (action.type === 'RESET_STATE') {
    state = undefined
  }

  return appReducer(state, action)
}

function resetAndUpdateOneSlice() {
  return (dispatch, getState) {
    const slice = Object.assign({}, getState().slice) 
    //assuming your slice is an object
    //just want to demonstrate cloning your data before you reset your state.
    dispatch(resetState())
    dispatch(updateSliceOfState(slice))
  }
}

这是一个可能的解决方案 - 纯函数和 thunk 的混合 - 虽然我不确定你为什么要重置你状态的这么多部分。并不是说我在谴责你的决定,我只是想找出一个并非完全人为设计的用例。

以下是可能的,因为我们使用的是纯函数。

另外,我参考了这篇文章,因为它很有帮助。

希望对您有所帮助

我找到的最佳解决方案是在创建切片时利用 extraReducers 功能。这允许 slice 监听其他事件并实现我正在寻找的东西。

参考:https://redux-toolkit.js.org/api/createSlice#extrareducer

import { LOGOUT_USER } from '../redux/actions';
...
const reducerResult = createSlice({
      name: slice,
      initialState: initialState[state],
      reducers: this._generateReducers(),

      extraReducers: (builder) => {
        builder.addCase(LOGOUT_USER, (state, action) => {
          return { ...this.initialState };
        });

        // Default case if no other handlers matched
        //.addDefaultCase((state, action) => {});
      },
    });