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 badges1 Answer
Reset to default 0You 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
版权声明:本文标题:reactjs - Set constant from URL on prefetched site - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742381808a2464242.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论