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钩子:
- 先导入useNavigate:
import { useNavigate } from 'react-router-dom';
- 在组件内初始化navigate函数:
const Game = () => { const navigate = useNavigate(); // 你的现有代码... }
- 替换原来的
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
相关产品推荐
相关产品推荐

