React-Router中通过<Link>向类组件传递Props失败求助
问题分析与解决办法
你代码里的问题主要有三个:
构造函数未调用
super(props)
类组件的构造函数必须先调用super(props),否则无法在构造函数内访问this.props,这是你拿不到传递数据的首要原因。传递的state不在根props里
通过<Link>的state传递的数据,是存在this.props.location.state对象里的,不是直接挂在this.props下。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
相关产品推荐
相关产品推荐

