如何使用 <Link> 执行类似于 JS React 中的“ window.location = "/GameOverDied"; ”的操作?

问题描述 投票:0回答:1

目前我正在尝试用我在 React 中构建的游戏进行一些动画过渡,但我不想要

href
window.location
的重新渲染/刷新功能。在这方面我将如何使用
<Link>
中的
react-router-dom
处理?

const handleGameOver = () => {
  if (health < 1) {
    window.location = "/GameOverDied";
  } else if (fuel < 1) {
    window.location = "/GameOverFuel";
  } else {
  }
};

我还没有尝试过任何东西,因为我没有得到我在其他地方寻找的答案。

javascript reactjs hyperlink jsx react-router-dom
1个回答
0
投票

使用

useNavigate
挂钩从回调中发出 命令式 导航操作。

示例:

import { useNavigate } from 'react-router-dom';

...

const navigate = useNavigate();

...

const handleGameOver = () => {
  if (health < 1) {
    navigate("/GameOverDied", { replace: true });
  } else if (fuel < 1) {
    navigate("/GameOverFuel", { replace: true });
  } else {
  }
};

...
© www.soinside.com 2019 - 2024. All rights reserved.