如何使用Redux-Toolkit重置Redux Store

wkyowqbh  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(143)

我正在尝试将当前状态重置为初始状态。但所有尝试都不成功。我如何使用redux-toolkit进行重置?

const slice = createSlice({
  name: 'tweets',
  initialState: {
    byTweetId: {},
    byUserId: {},
    allTweetIds: [],
  },
  // reducers
  reducers: {
    // reset: (state) => Object.assign(state, initialState),
    tweetStoreReseted: (state) => {
      //here I need to reset state of current slice
    },
  },
});

字符串

mo49yndu

mo49yndu1#

单独创建一个初始状态,并在重置时使用它

const initialState = () => ({
    byTweetId: {},
    byUserId: {},
    allTweetIds: [],
});

const slice = createSlice({
    name: 'tweets',
    initialState: initialState(),
    reducers: {
        resetTweetStore: state => initialState()
    }
});

字符串

hk8txs48

hk8txs482#

这应该够了

const slice = createSlice({
  name: 'tweets',
  initialState: initialState,
  reducers: {
     tweetStoreReseted: () => initialState()
  }
});

字符串

wmtdaxz3

wmtdaxz33#

我尝试了许多解决方案,我发现在网络上,但没有一个工作后,尝试了。这是我最终发现的工作:

const slice = createSlice({
  name: 'tweets',
  initialState: {
    byTweetId: {},
    byUserId: {},
    allTweetIds: [],
  },
  // reducers
  reducers: {
    // reset: (state) => Object.assign(state, initialState),
    tweetStoreReseted: (state) => {
         state.byTweetId= {};
         state.byUserId= {};
         state.allTweetIds= [];
    },
  },
});

字符串

相关问题