我需要将当前状态重置为初始状态。但是我的所有尝试都不成功。我如何使用redux-toolkit来做这件事?
const showOnReviewSlice = createSlice({
name: 'showOnReview',
initialState: {
returned: [],
},
reducers: {
reset(state) {
//here I need to reset state of current slice
},
},
});
8条答案
按热度按时间pkbketx91#
大概是这样的:
kmynzznz2#
这对我很有效(2020年中晚期)。以您的代码上下文为例进行格式化。
q9rjltbz3#
直接用
initialState
替换state
对我来说 * 不 * 起作用(2020年中期)。我最后得到的工作是用Object.assign()
复制每个属性。这工作:64jmpszr4#
在我的情况下,正如前面的答案,2021年中期,只需设置初始状态**不工作,**即使您使用工具包适配器,如:
相反,您应该使用
Object.assign()
,猜测它与内部immer库行为相关qni6mghb5#
当使用多个切片时,可以使用extraReducers将所有切片恢复到其初始状态。
首先,创建一个可供所有切片使用的动作:
在每个切片中添加一个
initialState
,并使用revertAll
操作添加一个extraReducers
缩减器:可以照常创建存储区:
在react代码中,可以使用
useDispatch
钩子调用revertAll
操作:acruukt96#
我们要这样做。
假设您要在注销时清除所有数据。
在您的商店.tsx文件中:
然后创建如下形式的thunk:
0kjbasz67#
您可以对
initialState
使用跨页运算符oiopk7p58#
@i9或者我也有类似的问题,但是对于组合切片,我希望在调用日志时能够将状态重置为默认值
用于将reduxtoolkit-query与reducer组合在一起的代码