简体   繁体   中英

Conditional Rendering the components, Next.js style broken on first load

I am using Ant Design and Custom Stylesheet. On first load style is broken, but when I visit another page and come back to broken page, now it looks fine. So the problem is only on the first load. It's on the development server, I have been clear all cache. But still the same issue.

Here is the screenshot how it's looking like after first load

在此处输入图片说明

Here is the correct style after I come back from another page

在此处输入图片说明

Here is the code how I am rendering the components:

<div>
  {jwToken || role === "restaurant_owner" ? (
    <Layout>
      <Index />
    </Layout>
  ) : (
    <div>
      <Login />
    </div>
  )}
</div>

I had a simliar issue, the way I fixed it was to add a mounted variable that depended on the condition. So it looks this.

// Not sure how you pass the condition, I'm assuming hooks
const { condition } = someHook()

const [mounted, setMounted] = useState()

useEffect(() => {
   setMounted(true)
   return () => setMounted(false)
}, [condition]);

return (
   <div>
       {mounted && condition && <Component/>
   </div>
)

As to why this happens, I suspect it has to do with SSR (I found simliar issue on Github but for Material-UI ) and my solution forces the condition to be available only during the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM