React类组件未在构造器传props,为何render()中this.props未定义?
React类组件中this.props为undefined的原因分析
你的代码里this.props变成undefined,核心原因是构造函数没有将props传递给super()。
React的Component基类构造函数需要接收props参数,才能完成实例上this.props的初始化绑定。如果你的自定义构造函数调用super()时不传props,基类构造函数就无法把外部传入的props挂载到当前组件实例上,后续在render等方法里访问this.props自然就是undefined。
看你的代码示例:
class App extends React.Component { constructor(){ super() // 未传递props给父类构造函数 } render (){ console.log(this.props) // 结果为undefined } } <App name="ashwin"/>
解决方法
有两种简单的修复方式:
- 在构造函数中把
props传给super():
constructor(props){ super(props) }
- 直接删除自定义的构造函数——如果你的组件不需要在构造函数里做初始化状态、绑定事件等操作,React会使用默认构造函数,它会自动把
props传递给基类,确保this.props能正常访问。
内容的提问来源于stack exchange,提问作者ashwin sg
相关产品推荐
相关产品推荐

