在同级组件之间导航时,useNavigate 不会加载页面

发布于 2025-01-16 15:09:42 字数 905 浏览 2 评论 0原文

我正在使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

送舟行 2025-01-23 15:09:42

ShowItem 组件应该“侦听”itemId 路由参数的更改,以便它可以处理获取数据或运行依赖于该值的任何逻辑。

使用依赖于 itemId 路由参数的 useEffect 挂钩。

例子:

const { itemId } = useParams();

useEffect(() => {
  if (itemId) {
    // handle logic using new itemId value
  }
}, [itemId]);

The ShowItem component should "listen" for changes to the itemId 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 the itemId route param.

Example:

const { itemId } = useParams();

useEffect(() => {
  if (itemId) {
    // handle logic using new itemId value
  }
}, [itemId]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文