2023-11-30 记录实用小案例 —— react监听页面返回时执行事件

发布时间 2023-11-30 09:29:57作者: 哎呦你可棒棒了
  useEffect(() => {
    const handlePageBack = () => {
      // 此处写你想要触发的事件
    };

    // 监听浏览器的 popstate 事件,即页面返回事件
    window.addEventListener('popstate', handlePageBack);

    // 在组件卸载时移除事件监听
    return () => {
      window.removeEventListener('popstate', handlePageBack);
    };
  }, []);

当你要跳转到一个表单的时候,有没有给表单的返回按钮传值时(即不通过props传值),仅仅是用了history.back(),都可以触发浏览器事件popstate

注意:在pc端或移动端,你的回退或者前进都会触发popstate事件