You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何在if语句内实现页面跳转?Waldo游戏场景问题

解决React Router跳转GameOver页面失败的问题

首先得明确你使用的react-router-dom版本,不同版本的路由跳转方式差异很大,下面分两种情况给出修复方案:

情况1:使用react-router-dom v5

你的代码里用了props.history.push('/gameover'),但如果Game组件不是被<Route>直接渲染的,props里就不会自动注入history对象。解决方法有两个:

  • 方法一:确保Game组件通过Route直接渲染
    在路由配置里要写成:

    <Route path="/game" component={Game} />
    

    而不是把Game嵌套在其他非路由组件里。

  • 方法二:用withRouter高阶组件包裹Game组件
    如果必须嵌套,就导入withRouter并包裹组件:

    import { withRouter } from 'react-router-dom';
    
    const Game = (props) => {
      // 你的现有代码...
    }
    
    export default withRouter(Game);
    

情况2:使用react-router-dom v6

v6已经彻底移除了props.history和withRouter,需要改用useNavigate钩子:

  1. 先导入useNavigate:
import { useNavigate } from 'react-router-dom';
  1. 在组件内初始化navigate函数:
const Game = () => {
  const navigate = useNavigate();
  // 你的现有代码...
}
  1. 替换原来的props.history.push:
if (hit.current === 3) {
    console.log("running game over code");
    navigate('/gameover');
    console.log('gameover code after navigate');
}

额外检查点

  • 确认路由配置里已经正确添加了/gameover对应的路由组件:
    // 路由配置文件里
    <Route path="/gameover" element={<GameOver />} />
    
  • 检查hit.current是否确实能达到3,确保触发跳转的条件真的满足(可以通过console.log确认数值)。

内容的提问来源于stack exchange,提问作者Minchan Jung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 15:45:30