【问题标题】:How to use redux hooks in getInitialProps如何在 getInitialProps 中使用 redux 钩子
【发布时间】:2021-01-13 13:35:50
【问题描述】:

我一直在尝试通过重新加载来保持我的 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))
}

【问题讨论】:

    标签: redux react-redux next.js


    【解决方案1】:

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

    要在getInitialProps 中使用dispatch,请尝试使用此代码 sn-p 而不是使用useDispatch() 挂钩。

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

    【讨论】:

    • 感谢理查德的回复。由于某种原因,我的 ctx 不包含 store。这是否意味着我以错误的方式初始化我的商店?我也会看看这个库,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-06-04
    • 1970-01-01
    • 2019-11-11
    • 2021-05-15
    • 1970-01-01
    • 2019-01-01
    • 2020-06-09
    • 2021-05-27
    相关资源
    最近更新 更多