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

React-Router中通过<Link>向类组件传递Props失败求助

问题分析与解决办法

你代码里的问题主要有三个:

  1. 构造函数未调用super(props)
    类组件的构造函数必须先调用super(props),否则无法在构造函数内访问this.props,这是你拿不到传递数据的首要原因。

  2. 传递的state不在根props里
    通过<Link>的state传递的数据,是存在this.props.location.state对象里的,不是直接挂在this.props下。

  3. render中变量引用错误
    你直接写{userName},但这个变量并没有在render函数内定义,得从this.state或者this.props.location.state里取。


修正后的代码(分React Router版本)

如果你用的是React Router v5

v5的Route组件会自动给挂载的组件注入location、history等props,直接修改NewPage即可:

class NewPage extends React.Component<any, State> {
  constructor(props: any) {
    super(props); // 必须加这一行
    // 从location.state初始化组件state,加可选链避免直接访问/newPage时报错
    this.state = {
      userName: props.location?.state?.userName || '',
      userGender: props.location?.state?.userGender || '',
    };
  }

  render() {
    // 从state解构变量,方便后续使用
    const { userName, userGender } = this.state;
    return (
      <div>
        ...Content goes here...
        {userName} & {userGender}
      </div>
    );
  }
}

export default NewPage;

如果你用的是React Router v6

v6不再自动给组件注入location等props,类组件需要用withRouter高阶组件包裹才能拿到这些属性:

首先导入withRouter:

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

然后修改组件:

class NewPage extends React.Component<any, State> {
  constructor(props: any) {
    super(props);
    this.state = {
      userName: props.location?.state?.userName || '',
      userGender: props.location?.state?.userGender || '',
    };
  }

  render() {
    const { userName, userGender } = this.state;
    return (
      <div>
        ...Content goes here...
        {userName} & {userGender}
      </div>
    );
  }
}

// 用withRouter包裹组件,注入location等props
export default withRouter(NewPage);

额外提示

如果不想把数据存到组件state里,也可以直接在render中使用传递的state:

render() {
  // 解构location.state,加默认值避免直接访问页面时报错
  const { userName = '', userGender = '' } = this.props.location.state || {};
  return (
    <div>
      ...Content goes here...
      {userName} & {userGender}
    </div>
  );
}

这样就不用维护组件state,直接用传递过来的值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:50:21