首页 > 解决方案 > 如何在 getInitialProps 中使用 redux 钩子

问题描述

我一直在尝试通过重新加载来坚持我的 redux 商店。我最初使用 useEffect 来调度我的操作,但是当我尝试重新加载页面路由器时,它变得未定义,并且出现 500 错误。之后我尝试使用 getInitialProps 并使用 ctx.query.id 但我遇到了另一个错误,说只能在函数组件的主体内部调用挂钩。

如何让它在 getInitialProps 内部工作,以及通过重新加载持久保存我的商店数据的最佳方式是什么?

export default function CarPage() {
  const dispatch = useDispatch()
  const router = useRouter()
  const car = useSelector((state) => state.cars.car)

  /*
  useEffect(() => {
    if(!car && router) {
      dispatch(getCar(router.query.id))
    }
  }, [])
  */

  return (
      <Container>
        <h2>{car.model}</h2>
      </Container>
  )
}

CarPage.getInitialProps = async (ctx) => {
  const dispatch = useDispatch()
  dispatch(getCar(ctx.query.id))
}

标签: reduxreact-reduxnext.js

解决方案


要通过页面重新加载来持久化 redux 存储,我们肯定需要使用浏览器存储。我建议使用https://github.com/rt2zz/redux-persist

要使用dispatchinside getInitialProps,请尝试使用此代码片段而不是使用useDispatch()钩子。

CarPage.getInitialProps = async ({ store, query }) => {
   store.dispatch(getCar(query.id));
   return { initialState: store.getState() };
}

推荐阅读