reactjs - 如何在 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;
},
},
});
当我分派我的搜索操作时,它会返回我的新状态,但是当我清除搜索字段时,它会返回一个空数组,但我想返回我以前的状态。我是新手。提前致谢。
解决方案
您通常应该避免将过滤后的数据保存在 reducer 中。相反,将原始数据保留在reducer中,然后根据需要在reducer外部(例如在组件中)过滤数据。这样,如果需要,您始终可以使用原始数据。
作为旁注,我们建议使用extraReducers
默认的“构建器回调”形式,而不是“对象”形式:
https://redux-toolkit.js.org/api/createSlice#the-extrareducers-builder-callback-notation
推荐阅读
- reactjs - 为 Azure 中托管的 create-react-app 设置环境变量不起作用
- julia - Plots.jl:删除系列图例,保留颜色条
- java - 数组中的最后一个对象替换所有其他对象
- java - 从命令行检查 Java 3rd 方库版本
- dask - 是否可以从本地计算机远程启动 hpc (slurm) 上的 dask 集群?
- ios - 如果应用被 iOS 13 杀死,VoIP 推送将停止传送到应用
- json - 如何减慢我的 json 调用之间的毫秒数?
- blazor - 如何在 Blazor 应用程序的 HTML 标记中引用 C# 变量?
- javascript - 如果满足条件,有什么方法可以为特定列表项添加边框?
- ios - Xamarin 表单视频缩略图:尝试在 IOS 13.1.3 设备上创建视频缩略图表单本地存储时出错