是否有办法在使用redux-thunk
中间件的组件中侦听某些动作?或者我真的需要使用redux-saga
或redux-observable
来实现这一点吗?
这是我的redux-thunk异步动作,我只是简单地想关闭对话框后TICKET_CREATE_SUCCESS
动作分派
export const createTicketEffects = (ticket: Ticket): ThunkAction<void, RootState, unknown, Action<string>> => {
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
dispatch(TicketActions.createTicket(ticket));
return await TicketService.create(ticket)
.then(({ data }) => {
dispatch(TicketActions.createTicketSuccess(data.data, data.message));
})
.catch((error) => dispatch(TicketActions.createTicketError(error)));
};
};
感谢不是你问的那个意思,不是。组件不能"监听分派的操作"。
但是,thks可以返回一个promise,并且您可以等待该promise从dispatch(someThunk())
返回:
- https://redux.js.org/tutorials/essentials/part-5-async-logic checking-thunk-results-in-components
- https://redux.js.org/tutorials/fundamentals/part-7-standard-patterns thunks-and-promises
另外,请注意,您可以使用Redux Toolkit的createAsyncThunk
API来简化此想法:
const createTicketEffects = createAsyncThunk(
'tickets/createTickets',
async (ticket: Ticket) => {
const response = await TicketService.create(ticket);
return res.data; // example: not sure what you're doing with `res.message`
}
)