Nic*_*kiy 8 reactjs redux react-redux redux-toolkit
例如,我有这个切片,我想在 setUser 中使用 dispatch。我怎样才能做到这一点?
const contactsSlice = createSlice({
name: 'contacts',
initialState: initialState,
reducers: {
setUsers: (state, { payload }) => {
// I want to use dispatch here
dispatch()
},
toggleFavorite: (state, { payload }) => {
//
},
toggleCheck: (state, { payload }) => {
//
}
}
})
Run Code Online (Sandbox Code Playgroud)
你不能,你实现了一个dispatch功能不可用的减速器。阅读什么是减速器。
相反,在 React 代码中添加逻辑:
useEffect(() => {
dispatch(contactsSlice.actions.setUser());
dispatch(loginSlice.actions.logicAction());
}, []);
Run Code Online (Sandbox Code Playgroud)
或者,在目标切片中添加一个额外的减速器。
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
},
},
});
Run Code Online (Sandbox Code Playgroud)
或者写一个中间件,像createAsyncThunk,dispatch并getState可用功能下thunkAPI。
| 归档时间: |
|
| 查看次数: |
3311 次 |
| 最近记录: |