next.js 从外部url返回时的事件

wfveoks0  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(73)

从外部页面返回时如何调用函数?我用的是Next JS 12。
当我单击浏览器的后退按钮时,我看到缓存的页面,并且函数没有调用

const MyTest = () => {
  const router = useRouter();

  useEffect(() => {
    
    // my function
    
  }, [router]);

  return (
    <div className="container">
      <Button
        onClick={() => {
          window.location.assign("https://www.google.com");
        }}
      >
        Navigate page
      </Button>
    </div>
  );
};
jchrr9hc

jchrr9hc1#

您可以使用poststate event

useEffect(() => {
  const myFunction = () => {
    // Your function logic here
    console.log('Function called when returning from external page');
  };

  // Attach the event listener to the window's popstate event
  window.addEventListener('popstate', myFunction);

  // Remove the event listener when the component unmounts
  return () => {
    window.removeEventListener('popstate', myFunction);
  };
}, []);

相关问题