在同级组件之间导航时,useNavigate 不会加载页面
我正在使用react-router-dom v6开发一个react-js应用程序,
我尝试简化我的框架以使其更清晰。
MainRouter.js
<BrowserRouter>
<NavBar/>
<Routes>
<Route exact path="/" element={<HomePage/>}></Route>
<Route path="item" element={<ShowItem/>}>
<Route path=":itemId" element={<ShowItem/>}>
</Route>
</Route>
</Routes>
导航栏包含一个搜索栏,我可以搜索不同的项目:“item/1”、“item/2”...为了简单起见,我替换了搜索带有一个按钮的栏,该按钮尝试始终重定向到项目 12
NavBsr.js
return (
[...]
<button onClick={()=>navigate("/item/12")}>Click</button>
);
如果我位于除“item/*”之外的任何页面,导航将按预期工作。前任。如果我在“主页”,按钮会重定向到“item/12”
但是,如果我当前的页面是“item/*”,例如,会发生奇怪的行为。 “项目/1”。在这种情况下,如果我按下按钮,网址将更改为“item/12”,但内容不会加载:仅当我手动刷新页面时才会加载正确的内容
感谢您的任何建议
I'm working at a react-js app using react-router-dom v6
I try to simplify my framework to make it clearer.
MainRouter.js
<BrowserRouter>
<NavBar/>
<Routes>
<Route exact path="/" element={<HomePage/>}></Route>
<Route path="item" element={<ShowItem/>}>
<Route path=":itemId" element={<ShowItem/>}>
</Route>
</Route>
</Routes>
The navbar includes a search bar s.t. I'm able to search different items: "item/1", "item/2", ... For sake of semplicity, I replace the search bar with a button which try to redirect always to item 12
NavBsr.js
return (
[...]
<button onClick={()=>navigate("/item/12")}>Click</button>
);
If I'm in any page but "item/*", the navigation works as expected. Ex. if I'm at "homepage", the button redirects to "item/12"
However, the strange behaviour happens if my current page is "item/*", ex. "item/1". In this case, if I press the button the url changes to "item/12" but the content doesn't load: the correct content is loaded only if I manually refresh the page
Thanks for any suggestion
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ShowItem
组件应该“侦听”itemId
路由参数的更改,以便它可以处理获取数据或运行依赖于该值的任何逻辑。使用依赖于
itemId
路由参数的useEffect
挂钩。例子:
The
ShowItem
component should "listen" for changes to theitemId
route param so it can handle fetching data or running any logic that depends on this value.Use an
useEffect
hook with a dependency on theitemId
route param.Example: