假设我有以下代码:
const [showChild1, setShowChild1] = useState(false)
const [showChild2, setShowChild2] = useState(false)
<ParentComponent>
{showChild1 && <Child1 />}
{showChild1 && <Child2 />}
....
</ParentComponent
假设我正在浏览器中查看 Child2
,但我想返回查看 Child1
。如何使用浏览器的后退和前进按钮在有条件呈现的组件之间导航?截至目前,当我点击后退按钮时,我被推送到路径 /
。
最佳答案
您可以将事件监听器添加到全局窗口对象。事件名称为“popstate”,代码示例如下:
useEffect(() => {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', yourEvent);
return () => {
window.removeEventListener('popstate', yourEvent);
};
}, []);
关于javascript - 如何将浏览器历史记录与组件一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68883737/