Next.js:使用带有TypeScript的next-redux-wrapper在getServerSideProps中调用Thunk吗?

时间:2020-06-11 20:10:42

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

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

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 => {
    ...
  };
};

1 个答案:

答案 0 :(得分:1)

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

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

export type AppThunkDispatch = ThunkDispatch<ApplicationState, void, AnyAction>

然后在getServerSideProps(或getInitialProps)内部使用它时,只需将store.dispatch投射到它上即可。

const thunkDispatch = store.dispatch as AppThunkDispatch

我没有用getServerSideProps尝试过,但是我假设传递给它的存储与传递给getInitialProps的存储是一样的...