简体   繁体   中英

React.js Component not being created

I have an array of objects I wanted to display in a table. I have the following code

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.data
    };
  }

  render() {
    return (
      <table>
          {this.state.data.map(row => {
            console.log(row);
            <Test/>
          })}
      </table>
    );
  }
}

class Test extends React.Component {
  constructor(props) {
    super(props);
    console.log("7");
  }

  render() {
    return;
  }
}

The console.log() in the Table prints out all my data correctly, however, the console.log() in my Test constructor never prints.
Why is the Test not being created?


My proper rows is below:

class Rows extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.rowData
    };

    console.log("2");
  }

  render() {
    return (
      <tr>
        <td>{this.state.data.paymentFrom}</td>
        <td>{this.state.data.paymentTo}</td>
        <td>{this.state.data.paymentPeriod}</td>
        <td>{this.state.data.paymentAmount}</td>
      </tr>
    );
  }
}

For the Test component to be rendered correctly, you must to return the component, if it never return on the function body, will never gonna print.

Try this way:

class Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: this.props.data
    };
  }

  render() {
    return (
      <table>
          {this.state.data.map(row => {
            console.log(row);

            return (<Test/>)
          })}
      </table>
    );
  }
}

class Test extends React.Component {
  constructor(props) {
    super(props);
    console.log("7");
  }

  render() {
    return;
  }
}

您需要return <Test/>才能启动和渲染。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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