通过自己点击链接来重新渲染React Router组件。
<p>我用 <code>react-router-dom</code> v6</p>
<h1>代码</h1>
<pre class="brush:php;toolbar:false;"><NavLink to="/pathOne" className="ripple">label1</NavLink>
<NavLink to="/pathTwo" className="ripple">label2</NavLink></pre>
<h1>问题</h1>
<p>当你点击一个链接或另一个链接时,Route组件会按预期进行渲染。但是,如果"/pathOne"处于活动状态并且我再次点击它,什么都不会发生。</p><p>是否有一种方法可以通过点击活动链接来强制重新渲染路由元素?</p><p>如果设置了reloadDocument属性,我可以刷新整个页面,但这不是一个可行的选项。</p><p><code></code></p>
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 newlocation
object reference is created. The newlocation
object reference is enough to trigger the component using it to be rerendered.Example: