admin管理员组

文章数量:1335349

I have a multi page application, where a page has to pass a variable (road) to a dynamic page. I just grabbed the value from the URL, but as I changed the page to prefetch, it broke, since the URL is not available on first rendering.

function Main() { 
  const road =
      typeof window !== "undefined"
        ? window.location.pathname.split("/")[1] || ""
        : "";

  const fetchData = async () => {/*fetches using road*/};
  
  useEffect(() => {
    fetchData();
  }, []);

  return (/*Returns HTML and is using road*/);
}

I tried to set my const recursive and then trigger my function with a useEffect, but this doesn't work because my main can't be async.

I have a multi page application, where a page has to pass a variable (road) to a dynamic page. I just grabbed the value from the URL, but as I changed the page to prefetch, it broke, since the URL is not available on first rendering.

function Main() { 
  const road =
      typeof window !== "undefined"
        ? window.location.pathname.split("/")[1] || ""
        : "";

  const fetchData = async () => {/*fetches using road*/};
  
  useEffect(() => {
    fetchData();
  }, []);

  return (/*Returns HTML and is using road*/);
}

I tried to set my const recursive and then trigger my function with a useEffect, but this doesn't work because my main can't be async.

Share Improve this question asked Nov 20, 2024 at 4:30 Tim HeidTim Heid 113 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You can also do conditional rendering for the main component like this-

if(!url) {
return <p>Something went wrong...</p>
}
return (/*Returns HTML and is using road*/);

You can also change url with the component that you want to load first and then render that. Also you can use loading state to handle this.

本文标签: reactjsSet constant from URL on prefetched siteStack Overflow