useRouter/withRouter receive undefined on query in first render

坚强是说给别人听的谎言 提交于 2020-07-22 05:30:07

问题


I got a problem with my dynamic route. It look like this

[lang]/abc

I am trying to get query value from [lang] but when I using useRouter/withRouter i got query during 2-3 render of page ( on first i got query.lang = undefined ). its possible to get in 1 render or use any technique ?


回答1:


At the moment, it's not possible to get a query value at the first render.

Pages that are statically optimized by Automatic Static Optimization will be hydrated without their route parameters provided, i.e query will be an empty object ({}).

After hydration, Next.js will trigger an update to your application to provide the route parameters in the query object.

Also, at first render of a dynamic route router.asPath and router.route are equal. When query object would be available, router.asPath would reflect that.

You can rely on the query value within a useEffect hook after asPath has been changed.

const router = useRouter();

useEffect(() => {
  if (router.asPath !== router.route) {
    // router.query.lang is defined
  }
}, [router])

GitHub Issue - Add a "ready" to Router returned by "useRouter"




回答2:


I resolved my problem that I need it in Hoc component. I wrapped using withRouter(withLocale(Comp)) and create conditional in HOC

export default function withLocale(WrappedPage) {
    const WithLocale = ({ router, ...props }) => {
        const { lang } = router.query;
        if (!lang || !isLocale(lang)) {
            return <Error statusCode={404} />;
        }
        return (
            <LocaleProvider lang={lang}>
                <WrappedPage {...props} />
            </LocaleProvider>
        );
    };
   return WithLocale;
}



回答3:


In NextJS 9, one way to ensure route parameters are immediately available for page components is to get them from the context arg passed to getServerSideProps() and pass to the component as props.

For a page like [id].js,

export function getServerSideProps(context) {
  return {
    props: {params: context.params}
  };
}

export default ({params}) => {
  const {id} = params;
  return <div>You opened page with {id}</div>;
};


来源:https://stackoverflow.com/questions/61040790/userouter-withrouter-receive-undefined-on-query-in-first-render

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!