10

例如,我有这个切片,我想在 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 }) => {
      //
    }
  }
})
4

1 回答 1

7

你不能,你实现了一个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.

于 2020-05-16T09:12:41.773 回答