【问题标题】:Next.js: Calling Thunks in getServerSideProps with next-redux-wrapper with TypeScript?Next.js:在 getServerSideProps 中使用带有 TypeScript 的 next-redux-wrapper 调用 Thunks?
【发布时间】:2020-10-01 14:09:32
【问题描述】:

我正在尝试使用 next-redux-wrapper 商店从 Next.js 中的 getServerSideProps 发送 thunk。但是,我不断收到以下打字稿错误:

TS2345: Argument of type '(dispatch: any) => Promise<any>' is not assignable to parameter of type 'AnyAction'.   Property 'type' is missing in type '(dispatch: any) => Promise<any>' but required in type 'AnyAction'.

我之前没有在 Redux 中使用过 TypeScript,所以不确定我在这里做错了什么......

我的代码如下:

// page.tsx

export const getServerSideProps = wrapper.getServerSideProps(
  async ({ store, params }) => {
    store.dispatch(myThunkFunction(params.id));

    return {
      props: {
        id: params.id,
      },
    };
  });
// thunks.ts

export const myThunkFunction = id => {
  return async dispatch => {
    ...
  };
};

【问题讨论】:

    标签: reactjs typescript redux next.js redux-thunk


    【解决方案1】:

    It seems to be a known issue with next-redux-wrapper when using redux-thunk,其中next-redux-wrapper 在getServerSideProps(或getInitialProps,因为这是我正在使用的)返回的dispatch 类型不是ThunkDispatch。

    我花了很多时间试图找出问题所在,并通过创建类似的应用程序 thunk 调度类型设法找到解决方法

    export type AppThunkDispatch = ThunkDispatch&lt;ApplicationState, void, AnyAction&gt;

    当在getServerSideProps(或getInitialProps)中使用它时,您只需将store.dispatch 转换为它。

    const thunkDispatch = store.dispatch as AppThunkDispatch

    我没有用getServerSideProps 尝试过,但我假设传递给它的商店与传递给getInitialProps 的商店相同...

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 2022-01-22
      • 2022-01-26
      • 2020-05-16
      • 1970-01-01
      • 2018-06-04
      • 2022-10-24
      • 1970-01-01
      • 2021-11-06
      相关资源
      最近更新 更多