gpt4 book ai didi

reactjs - Redux 工具包 : How to refer action created with createAction as type

转载 作者:行者123 更新时间:2023-12-03 23:35:05 24 4
gpt4 key购买 nike

Redux 工具包提供 createAction辅助方法。我在引用使用 createAction 创建的操作时遇到问题作为类型。
例如 :

const getData = createAction<PayloadAction<number>>('user/getData')

function* exampleSaga(action: ?) {
...
}
我怎么知道 exampleSagaaction 类型getData ?

要查看我是如何尝试这样做的,请参阅以下(示例)代码并查看我所面临问题的评论:
reducer .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);
}

最佳答案

这就是使用 getData 的返回类型获取它的方式。

function* exampleSaga(action: ReturnType<typeof getData>) {

...

}

关于reactjs - Redux 工具包 : How to refer action created with createAction as type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60377370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com