简体   繁体   English

无法读取未定义反应的属性道具

[英]cannot read property props of undefined react

Currently learning react 'props'. 当前正在学习反应“道具”。 When rendering props inside a component i get an error on compile when passing 'name' and 'age': 在组件内渲染道具时,传递“名称”和“年龄”时出现编译错误:

"Cannot read property 'name' of undefined." “无法读取未定义的属性'名称'。”

Here is my code: 这是我的代码:

Dashboard 仪表板

import React, { Component } from 'react';
import SummaryWidget from '../../Components/SummaryWidgets/SummaryWidget';

class Dashboard extends Component {
  constructor(props) {
    super(props);
  }

  render() {

    return (
      <div className="animated fadeIn">
        <Row>
          <Col xs="12" sm="6" lg="6">

            <SummaryWidget name='David' age='20'/>


          </Col>

          <Col xs="12" sm="6" lg="6">


          </Col>

        </Row>

      </div>
    )
  }
}
export default Dashboard;

SummaryWidget 摘要小部件

import React, { Component } from 'react';

class SummaryWidget extends Component {

  constructor(props) {
    super(props);
  }

  render (props) {
    return (
      <div className="SummaryWidget">
      <span>{props.name}{props.age}</span>
      </div>
    )
  }

}

export default SummaryWidget;

Please change render method to 请更改渲染方法为

render () {
    return (
      <div className="SummaryWidget">
      <span>{this.props.name}{this.props.age}</span>
      </div>
    )
  }

BTW: If you do not want to do anything in the constructor, you do not have to implement it. 顺便说一句:如果您不想在构造函数中做任何事情,则不必实现它。 Also, if you do not need states and any life cycle method, you should make your component as a stateless component. 另外,如果不需要状态和任何生命周期方法,则应使组件成为无状态组件。 Like: 喜欢:

import React from 'react';

const SummaryWidget = ({ name, age }) => (
  <div className="SummaryWidget">
    <span>{name}{age}</span>
  </div>
);

export default SummaryWidget;

Change your SummayWidget Component from 从更改您的SummayWidget组件

class SummaryWidget extends Component {

  constructor(props) {
    super(props);
  }

  render (props) {
    return (
      <div className="SummaryWidget">
      <span>{props.name}{props.age}</span>
      </div>
    )
  }

}

to

class SummaryWidget extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div className="SummaryWidget">
      <span>{this.props.name}{this.props.age}</span>
      </div>
    )
  }

}

You do not need to add render (props) like this in a class component. 您无需在类组件中添加这样的render (props)属性)。

If you need a class component do like above, or if you need a functional component do like @kevin suggested. 如果需要类组件,请执行上述操作,或者,如果需要功能组件,请执行@kevin建议的操作。

working demo 工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM