Redux 工具包提供了createAction
辅助方法。我无法将使用createAction
as 类型创建的操作引用。
例如:
const getData = createAction<PayloadAction<number>>('user/getData')
function* exampleSaga(action: ?) {
...
}
我怎么知道exampleSaga
那action
是类型getData
?
要查看我是如何尝试这样做的,请参阅以下(示例)代码并查看我所面临问题的评论:
减速器.ts
import { createAction, PayloadAction } from '@reduxjs/toolkit';
export const getData = createAction<PayloadAction<number>>('user/getData');
const userSlice = createSlice({
name: userSliceName,
initialState,
reducers: {
getUser(state: IUserState): void {
state.loading = true;
state.error = null;
},
getUserSuccess(state: IUserState, action: PayloadAction<{ user: IUser }>): void {
const { user } = action.payload;
state.user = user;
state.loading = false;
state.error = null;
},
getUserFailure(state: IUserState, action: PayloadAction<string>): void {
state.loading = false;
state.error = action.payload;
},
},
});
export type UserSaga = Generator<
| CallEffect<IUser>
| PutEffect<typeof getUserSuccess>
| PutEffect<typeof getUserFailure>
| ForkEffect<never>
>;
sagas.ts
import { UserSaga, getData } from './reducer.ts';
// For the following fetchUser saga arguments, how can I define that 'action' is of type getData, imported from the above 'reducer.ts' file.
function* fetchUser(action: PayloadAction<typeof getData>): UserSaga {
try {
const userId = action.payload;
// Problem is here
// I expect userId to be of type number, whereas it is:
// ActionCreatorWithPayload<{payload: number, type: string}>
...
} catch (e) {
...
}
}
function* userSaga(): UserSaga {
const pattern: any = getData.type;
yield takeLatest(pattern, fetchUser);
}