首页 > 解决方案 > 如何在 createSlice reducer 中使用 dispatch?

问题描述

例如,我有这个切片,我想在 setUser 中使用调度。我怎样才能做到这一点?

const contactsSlice = createSlice({
  name: 'contacts',
  initialState: initialState,
  reducers: {
    setUsers: (state, { payload }) => {
      // I want to use dispatch here
      dispatch()
    },
    toggleFavorite: (state, { payload }) => {
      //
    },
    toggleCheck: (state, { payload }) => {
      //
    }
  }
})

标签: reactjsreduxreact-reduxredux-toolkit

解决方案


你不能,你实现了一个dispatch功能不可用的减速器。阅读什么是减速器

相反,在 React 代码中添加逻辑:

useEffect(() => {
  dispatch(contactsSlice.actions.setUser());
  dispatch(loginSlice.actions.logicAction());
}, []);

或者,在目标 slice中添加一个额外的 reducer 。

const contactsSlice = createSlice({
  name: "contacts",
  initialState: initialState,
  reducers: {
    setUsers: (state, { payload }) => {
      // setUsers logic
    },
  },
});

const loginSlice = createSlice({
  name: "login",
  initialState: initialState,
  extraReducers: {
    "contacts/setUsers": (state, { payload }) => {
      // Same logic
    },
  },
});

或者编写一个中间件,比如createAsyncThunkdispatch以及getStatethunkAPI.


推荐阅读