通过自己点击链接来重新渲染React Router组件。
P粉295728625
P粉295728625 2023-07-27 22:31:16
[React讨论组]
<p>我用&nbsp;<code>react-router-dom</code> v6</p> <h1>代码</h1> <pre class="brush:php;toolbar:false;">&lt;NavLink to="/pathOne" className="ripple"&gt;label1&lt;/NavLink&gt; &lt;NavLink to="/pathTwo" className="ripple"&gt;label2&lt;/NavLink&gt;</pre> <h1>问题</h1> <p>当你点击一个链接或另一个链接时,Route组件会按预期进行渲染。但是,如果"/pathOne"处于活动状态并且我再次点击它,什么都不会发生。</p><p>是否有一种方法可以通过点击活动链接来强制重新渲染路由元素?</p><p>如果设置了reloadDocument属性,我可以刷新整个页面,但这不是一个可行的选项。</p><p><code></code></p>
P粉295728625
P粉295728625

全部回复(1)
P粉432906880

If all you really want is for the route component to rerender each time the link to its route is clicked then just have those components call the useLocation hook. Each time the link is clicked a new location object reference is created. The new location object reference is enough to trigger the component using it to be rerendered.

Example:

const PathOne = () => {
  useLocation();

  useEffect(() => {
    console.log("PathOne rerender");
  });

  return <h1>PathOne</h1>;
};

const PathTwo = () => {
  useEffect(() => {
    console.log("PathTwo rerender");
  });

  return <h1>PathTwo</h1>;
};
function App() {
  return (
    <div className="App">
      <NavLink to="/pathOne" className="ripple">
        label1
      </NavLink>
      <NavLink to="/pathTwo" className="ripple">
        label2
      </NavLink>
      <Routes>
        <Route path="/pathOne" element={<PathOne />} />
        <Route path="/pathTwo" element={<PathTwo />} />
      </Routes>
    </div>
  );
}

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号