reactjs - ThunkAction 通过调度返回,而不是 ThunkAction 的返回类型

标签 reactjs typescript react-redux

如何配置 Typescript 与 React-Redux 和 Redux-thunk 一起使用,以便 dispatch返回正在分派(dispatch)的 ThunkAction 的返回类型,而不是 ThunkAction<a,b,c,d,e>

export function addPerson(
  person: Person
): PersonActionTypes {
  return {
    type: ADD_PERSON,
    person,
  }
}


export const savePerson = (
  person: Person
): ThunkAction<
  Promise<Person>,
  RootState,
  unknown,
  Action<string>
> => async (dispatch): Promise<Person> => {
  const savedPerson = await PersonApi.save(person)
  dispatch(addPerson(savedPerson))
  return savedPerson
}

当我发送此操作时,我希望它返回 Promise<Person>但调度返回 ThunkAction<Promise<void>, RootState, unknown, Action<string>>

const savedPerson = await dispatch(savePerson(person))
// savedPerson is a ThunkAction as far as TypeScript is concerned but I would like it to be a Person.

最佳答案

遇到同样的问题。一段时间后找到了一个对我有用的解决方案。 这里的问题是,dispatch 默认情况下获取类型 Dispatch,并且对于简单操作来说是可以的,但对于 ThunkAction 则不行。

我的 thunk Action 是这样描述的:

type AppThunk<ReturnType = void> = ThunkAction<ReturnType, StateType, unknown, Action<string>>;
export const thunkAction = (id: number): AppThunk<Promise<{ status: string }>> => async (dispatch) => { ...do something, return correct type };

我已经为我的 thunk-dispatch 创建了类型

export type AppThunkDispatch = ThunkDispatch<StateType, unknown, Action<string>>;

之后我就能够使用返回值而不会出现类型错误,如下所示:

const data  = await (dispatch as AppThunkDispatch)(thunkAction(33));
if (data.status === 'success') { console.log('perfect') }

如果您在这个特定组件中只有 thunk 操作要分派(dispatch),那么您可以定义一次分派(dispatch)类型

const dispatch: AppThunkDispatch = useDispatch();

并避免(作为 AppThunkDispatch 调度) 转换

关于reactjs - ThunkAction 通过调度返回,而不是 ThunkAction 的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63025338/

相关文章:

typescript - 是否可以在 Typescript 中迭代 const 枚举?

javascript - typescript 代码 : How to calculate Totale=Sum(Subtotale) and price* quantita = subtotale Angular5

javascript - 将 own-props 命名空间与 state-props 分开是一种有用的模式吗?

javascript - react-redux:元素类型无效

reactjs - 在操作调用源自的 View 中处理 Redux Saga 结果

node.js - 通过电子邮件链接打开本地环境页面

javascript - 通过字符串路径访问和修改 JSON-Object

reactjs - 将处理函数移至 React 组件之外

javascript - React + Redux 不更新存储

javascript - 在 react 中使用 splice 添加到数组的正确方法是什么