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

ReactJS结合Twilio开发聊天应用报错:this.props.history未定义

问题原因

你当前使用的是react-router-dom v6版本,该版本移除了原有的withRouter高阶组件,也不会自动给Route指定的页面组件注入history、location等路由相关属性,所以类组件中读取this.props.history会报未定义错误。

修复步骤

  1. 自定义适配v6版本的withRouter高阶组件
    你可以在项目中新建一个工具文件,或者直接在WelcomeScreen.js、ChatScreen.js顶部添加如下代码:
import { useLocation, useNavigate, useParams } from "react-router-dom";

function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();
    return <Component {...props} router={{ location, navigate, params }} />;
  }
  return ComponentWithRouterProp;
}
  1. 修改两个页面组件的导出逻辑
    用上面写的withRouter包裹原有组件导出,让组件可以拿到路由属性:
  • WelcomeScreen.js末尾的导出改为:
export default withRouter(WelcomeScreen);
  • ChatScreen.js末尾的导出改为:
export default withRouter(ChatScreen);
  1. 替换原有路由操作的写法
    react-router-dom v6里不再用history.push/history.replace,统一用navigate方法实现跳转:
  • 修改WelcomeScreen.js的login方法:
    原代码this.props.history.push("chat", { room, email });替换为:
this.props.router.navigate("/chat", { state: { room, email } });
  • 修改ChatScreen.js里的跳转和取值逻辑:
    1. 原代码const { location } = this.props;替换为const { location } = this.props.router;
    2. 原代码this.props.history.replace("/");替换为:
    this.props.router.navigate("/", { replace: true });
    
  1. 可选优化:如果不想保留类组件写法,也可以直接将两个组件改写为函数组件,直接调用useNavigate、useLocation钩子实现路由操作,不需要额外封装withRouter。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:57:03