reactjs - 如何在 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 }) => {
//
}
}
})
解决方案
你不能,你实现了一个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
},
},
});
或者编写一个中间件,比如createAsyncThunk
,dispatch
以及getState
在thunkAPI
.
推荐阅读
- php - Mysql - 怎么做这个 sql
- java - 如何在类中使用 Javac 为命令行自动编译?
- python - 错误:包目录
不存在 - azure - Azure 服务总线主题订阅者接收消息不按顺序
- github-actions - Github Actions:检查步骤状态
- build - VSTS 中的条件构建
- python - Jaden Casing String:如何返回带有大写单词的句子字符串?
- kubernetes - 如何修复 NetworkUnavailable:kubernetes 节点中的 True 错误
- python-3.x - 试图抓取“hellopeter.com”无法深入了解实际评论
- python - 检测在哪里捕获了异常