问题描述
我需要输入一些道具和参数 这是代码的一部分。我应该如何正确编写 createAction?
const onSubmitHandler = (userFormData: TuserDataFromForm) => {
console.log("this work");
// here is error - userFormData
dispatch(asyncAction(userFormData));
};
function* watchFunc() {
// here is error - asyncAction.type
yield takeEvery(asyncAction.type,workFunc);
}
// What should I write instead of any
// to not get error here - dispatch(asyncAction(userFormData)) - in Component
// and here - takeEvery(asyncAction.type,workFunc) - in sagas
const asyncAction: any = createAction("ASYNC_ACTION");
完整代码如下:
解决方法
redux 工具包类型的编写考虑到您不应该自己定义它们。
写
const asyncAction = createAction<TuserDataFromForm>("ASYNC_ACTION");
没有必要在那里为变量指定类型。
以后,请检查 the API documentation - TypeScript 中几乎完全可用。
至于在 saga 中的用法,请执行以下任一操作
yield takeEvery(asyncAction,workFunc);
// or
yield takeEvery(asyncAction.match,workFunc);
您可能还想看看 typed-redux-saga,因为它与 TS 集成得更好:
import { take } from "redux-saga/effects";
function* exampleSaga() {
// cannot be inferred and needs to be manually typed
const action: IncrementActionType = yield take(slice.actions.incrementBy);
}
对比:
import { take } from "typed-redux-saga";
function* exampleSaga() {
// correctly inferred as { payload: number; type: string; }
const action = yield* take(slice.actions.incrementBy);
}