首页 > 解决方案 > 如何在 redux 工具包中返回默认状态?

问题描述

我是 redux 工具包的新手。在这里,我试图在清除搜索输入后返回我以前的状态。这是我的减速机,

const dataSlice = createSlice({
  name: "data",
  initialState: {
    datas: [],
  },
  reducers: {
    search: (state, action) => {
      console.log(action.payload);
      if (action.payload) {
        state.datas = state.datas.filter((data) => {
          return data.mission_name.toLowerCase().includes(action.payload);
        });
      }
    },
  },
  extraReducers: {
    [dataFetch.pending]: (state, action) => {
      state.loading = true;
    },
    [dataFetch.fulfilled]: (state, action) => {
      state.datas = action.payload;
      state.loading = false;
    },
    [dataFetch.rejected]: (state, action) => {
      state.error = action.payload;
    },
  },
});

当我分派我的搜索操作时,它会返回我的新状态,但是当我清除搜索字段时,它会返回一个空数组,但我想返回我以前的状态。我是新手。提前致谢。

标签: reactjsreduxreact-reduxredux-toolkit

解决方案


您通常应该避免将过滤后的数据保存在 reducer 中。相反,将原始数据保留在reducer中,然后根据需要在reducer外部(例如在组件中)过滤数据。这样,如果需要,您始终可以使用原始数据。

作为旁注,我们建议使用extraReducers默认的“构建器回调”形式,而不是“对象”形式:

https://redux-toolkit.js.org/api/createSlice#the-extrareducers-builder-callback-notation


推荐阅读