如何在 createSlice reducer 中使用 dispatch?
How to use dispatch in createSlice reducer?
例如,我有这个切片,我想在 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
功能不可用的减速器。读什么 reducers are.
改为在 React 代码中添加逻辑:
useEffect(() => {
dispatch(contactsSlice.actions.setUser());
dispatch(loginSlice.actions.logicAction());
}, []);
或者,在目标切片中添加一个额外的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
下可用。
例如,我有这个切片,我想在 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
功能不可用的减速器。读什么 reducers are.
改为在 React 代码中添加逻辑:
useEffect(() => {
dispatch(contactsSlice.actions.setUser());
dispatch(loginSlice.actions.logicAction());
}, []);
或者,在目标切片中添加一个额外的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
下可用。