首页 > 解决方案 > 如何将浏览器历史记录与组件一起使用?

问题描述

假设我有以下代码:

const [showChild1, setShowChild1] = useState(false)
const [showChild2, setShowChild2] = useState(false)

        <ParentComponent>
          {showChild1 && <Child1 />}
          {showChild1 && <Child2 />}
           ....
      </ParentComponent

假设我正在浏览Child2器中查看,但我想返回查看Child1. 如何使用浏览器的后退和前进按钮在有条件渲染的组件之间导航?截至目前,当我单击后退按钮时,我被推到了路径/

标签: javascriptreactjs

解决方案


您可以将事件侦听器添加到全局窗口对象。事件名称为“popstate”,代码示例如下:

  useEffect(() => {
    window.history.pushState(null, null, window.location.pathname);
    window.addEventListener('popstate', yourEvent);
    return () => {
      window.removeEventListener('popstate', yourEvent);  
    };
  }, []);

推荐阅读