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

React模态组件跳转页面并传递Props的实现问题

如何在无history props的组件中路由跳转并传递数据到Learning组件

看起来你遇到的核心问题是当前组件没有拿到history prop,没法通过路由跳转到Learning组件并传递接口获取的数据,我给你几种可行的解决方案:

方法1:使用withRouter高阶组件(React Router v5)

你的组件没有history prop,大概率是因为它没有直接被<Route>组件包裹渲染。React Router v5提供了withRouter这个高阶组件,能把history、location、match这三个路由相关的props注入到你的组件里。

具体步骤:

  1. 从react-router-dom导入withRouter:
import { withRouter } from 'react-router-dom';
  1. 在导出组件的时候,用withRouter包裹你的模态组件:
export default withRouter(YourModalComponent);

另外,注意你代码里的一个小错误:push的state里learningData:"data"是字符串,应该改成变量data,不然传过去的不是你接口获取的真实数据:

this.props.history.push({
    pathname:"/learning",
    state:{
        learningData: data, // 这里改为变量data
        learningType:Constants.LEARNING_TYPE.Learning,
        includeAlreadyLearned:includeLearned,
    }
});

方法2:适配React Router v6+的方案

如果你的项目已经升级到React Router v6,withRouter已经被移除了,这时候可以选这两种方式:

方式A:把类组件改成函数组件,使用useNavigate钩子

这是v6推荐的方式,代码会更简洁:

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

function YourModalComponent() {
  const navigate = useNavigate();

  const startInteligentLearning = async () => {
    const knowledgeIds = getIdsOfKnowledges(); // 调整为函数内的方法写法
    const includeLearned = disabledLearnedExercies; // 改用useState管理状态
    const data = await getDataForLearning(knowledgeIds); // 调整为函数内的异步方法
    navigate("/learning", {
      state: {
        learningData: data,
        learningType:Constants.LEARNING_TYPE.Learning,
        includeAlreadyLearned:includeLearned,
      }
    });
  };

  // 其他逻辑...
}

方式B:自定义高阶组件适配类组件

如果不想改动组件类型,可以自己封装一个高阶组件来传递navigate方法:

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

const withNavigate = (Component) => {
  return (props) => {
    const navigate = useNavigate();
    return <Component {...props} navigate={navigate} />;
  };
};

// 导出时使用这个高阶组件
export default withNavigate(YourModalComponent);

之后在你的类组件里就可以通过this.props.navigate跳转:

this.props.navigate("/learning", {
  state: {
    learningData: data,
    learningType:Constants.LEARNING_TYPE.Learning,
    includeAlreadyLearned:includeLearned,
  }
});

在Learning组件中接收传递的数据

不管用哪种跳转方式,都能在Learning组件里拿到传递的state:

  • 如果Learning是类组件:
componentDidMount() {
  // 加个默认值避免state为空时报错
  const { learningData, learningType, includeAlreadyLearned } = this.props.location.state || {};
  // 在这里处理数据,比如设置到组件state里
}
  • 如果Learning是函数组件:
import { useLocation } from 'react-router-dom';

function Learning() {
  const location = useLocation();
  const { learningData, learningType, includeAlreadyLearned } = location.state || {};
  // 处理数据...
}

内容的提问来源于stack exchange,提问作者Young L.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:17:49