Re-render the React Router component by clicking the link yourself.
P粉295728625
2023-07-27 22:31:16
<p>I use <code>react-router-dom</code> v6</p>
<h1>code</h1>
<pre class="brush:php;toolbar:false;"><NavLink to="/pathOne" className="ripple">label1</NavLink>
<NavLink to="/pathTwo" className="ripple">label2</NavLink></pre>
<h1>Question</h1>
<p>When you click one link or another, the Route component renders as expected. However, if "/pathOne" is active and I click on it again, nothing happens. </p><p>Is there a way to force a route element to be re-rendered by clicking on an active link? </p><p>I could refresh the entire page if the reloadDocument attribute was set, but that's not a viable option. </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: