【问题标题】:How to typescript createAction from redux-toolkit to not get errors如何从 redux-toolkit 编写 createAction 以不出错
【发布时间】:2020-12-31 15:43:42
【问题描述】:

我需要输入一些道具和参数这是代码的一部分。 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");

这里是完整的代码:

https://codesandbox.io/s/saga-redux-toolkit-actions-reducers-of-slices-2f7tx?file=/src/redux/actions.ts

【问题讨论】:

    标签: typescript saga redux-toolkit


    【解决方案1】:

    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);
    }
    

    【讨论】:

    • 是的,我最近找到了答案,我应该只在这里输入 const asyncAction = createAction("ASYNC_ACTION"); thnx 的详细答案我想投票,但我没有足够的声誉
    • 接受正确的答案应该没问题;)
    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 2020-09-13
    • 2020-04-24
    • 2021-09-17
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多