Next.js搭配next-redux-wrapper+TS时getServerSideProps报错如何解决
问题根因
你写的getServerSideProps回调函数执行完异步dispatch之后没有返回值,返回类型为void,但Next.js要求getServerSideProps必须返回符合GetServerSidePropsResult类型的对象,必须包含props/redirect/notFound三个字段中的至少一个。
修复方案
修改category.tsx中的getServerSideProps代码,执行完dispatch后添加返回值即可:
// category.tsx export const getServerSideProps = wrapper.getServerSideProps( (store) => async ({ req }) => { await store.dispatch(fetchCategory()) // 必须返回符合规范的对象,没有需要传给页面的参数就返回空props return { props: {} } } )
可选优化(避免后续dispatch类型报错)
如果后续调用store.dispatch时还有TypeScript类型不兼容的问题,是因为默认的Store Dispatch类型没有兼容redux-thunk的异步返回,需要补充ThunkDispatch类型定义:
// store.ts 补充类型定义 import type { ThunkDispatch } from 'redux-thunk' import type { AnyAction } from 'redux' export type AppDispatch = ThunkDispatch<RootState, unknown, AnyAction>
另外注意你reducers.ts里的拼写错误:categoriesReudcer应为categoriesReducer,避免运行时报错。
内容的提问来源于stack exchange,提问作者hakuu1251
相关产品推荐
相关产品推荐

