javascript - 如何将浏览器历史记录与组件一起使用?
问题描述
假设我有以下代码:
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);
};
}, []);
推荐阅读
- django - Django 模型和外键
- python - 如何将用户输入添加到列表中?Python
- java - Android java mediaplayer - onPrepared() 后多次触发 onCompletionListener
- c# - 如何在滚动视图 xamarin.forms 中绑定编辑器控件?
- active-directory - Intune 用户密码设置问题
- sql - PySpark AND EXISTS 等价于 sql 查询
- node.js - 如何在移动设备上使用 React 和 materialUI 使 GridList 在一行中垂直面对
- javascript - Ajax 和 Django 中的模式窗口问题
- azure-pipelines - 在不同 Azure Pipeline 作业之间共享 node_modules 的有效方法
- swift - 鼠标悬停在 NSButton 更改光标上(对于 OSX)