英文:
React Router rerender component by self-clicking a link
问题
我使用 react-router-dom
v6
代码
<NavLink to="/pathOne" className="ripple">label1</NavLink>
<NavLink to="/pathTwo" className="ripple">label2</NavLink>
问题
当您点击一个链接或另一个链接时,Route
组件会正常渲染。但如果 /pathOne
已经处于活动状态,我再次点击它会发生什么?什么都不会发生。
有没有一种方法可以通过点击活动链接来强制重新渲染路由元素?
如果设置 reloadDocument
属性,我可以刷新整个页面,但这不是一个选项。
英文:
I use react-router-dom
v6
The Code
<NavLink to="/pathOne" className="ripple">label1</NavLink>
<NavLink to="/pathTwo" className="ripple">label2</NavLink>
The Problem
When you click one link or another, the Route
component renders just as it should. But what if "/pathOne"
is active and I click on it again? Nothing happens.
Is there a way to force rerender route element by clicking on active link?
I can refresh all page if I set reloadDocument
prop but this is not an option.
答案1
得分: 3
如果你真正想要的是在点击其路由链接时重新渲染路由组件,那么只需让这些组件调用useLocation
钩子。每次单击链接时,都会创建一个新的location
对象引用。新的location
对象引用足以触发使用它的组件重新渲染。
示例:
const PathOne = () => {
useLocation();
useEffect(() => {
console.log("PathOne 重新渲染");
});
return <h1>PathOne</h1>;
};
const PathTwo = () => {
useEffect(() => {
console.log("PathTwo 重新渲染");
});
return <h1>PathTwo</h1>;
};
function App() {
return (
<div className="App">
<NavLink to="/pathOne" className="ripple">
标签1
</NavLink>
<NavLink to="/pathTwo" className="ripple">
标签2
</NavLink>
<Routes>
<Route path="/pathOne" element={<PathOne />} />
<Route path="/pathTwo" element={<PathTwo />} />
</Routes>
</div>
);
}
英文:
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>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论