Dynamic Importing of an unknown component - NextJs

前端 未结 3 1703
心在旅途
心在旅途 2021-01-20 01:05

I want to load a component dynamically based on the route. I\'m trying to make a single page which can load any individual component for testing purposes.

However whe

3条回答
  •  难免孤独
    2021-01-20 01:38

    It happens because router.query is not ready and router.query.component is undefined at the very first render of dynamic page.

    This would print false at first render and true at the following one.

     console.log(path === '../../components/common/CircularLoader');
    

    You can wrap it with useEffect to make sure query is loaded.

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

    SO: useRouter receive undefined on query in first render

    Github Issue: Add a ready: boolean to Router returned by useRouter

提交回复
热议问题