undefined React JS变量

时间:2018-06-04 10:24:45

标签: javascript reactjs components undefined jsx

这是我第一次使用Javascript / React JS进行编码,所以我不确定这里有什么问题。 getLicensees()向我的API发送GET请求并返回所有被许可方。到目前为止,控制台日志正在工作并打印正确的值。

constructor(props) {
super(props);

this.state = {licensees: []};

let licenseeResponse = LicensingService.getLicensees()
  .then(licensees => {
    this.state.licensees = licensees;
    console.log("component", licensees);
    console.log(licensees[0].city);
  });
}

我试图从我的被许可人对象中的所有信息中生成一个表。但我不能在我的render()方法中使用this.state.licensees[0].city

render() {
return (
  <main id="content">
    <div id="head">
      <h4 className="headline">
        Liste aller Lizenznehmer
      </h4>

      <div className="licenseeTable">
        <table>
          <tr>
            <th>Lizenz nehmer</th>
            <th>Aktuelles Zertifikat</th>
            <th>Details</th>
          </tr>
          <tr>
            <td>{this.state.licensees[0].city}</td>
            <td>test2</td>
            <td>test3</td>
          </tr>
        </table>
      </div>
    </div>
  </main>
);
}

我该如何正确地做到这一点?

- 我的解决方案:

componentDidMount() {
console.log('component did mount..', this);
LicensingService.getLicensees()
  .then(licensees => {
    this.setState({licensees});
    console.log(licensees);
  });
}

...

{
            this.state.licensees.map(license => {
              return <tr>
                <td>{license.company}</td>
                <td>{license.testCertificate.toString()}</td>
                <td>{license.city}</td>
              </tr>
            })
          }

this.setState({licensees})是为状态对象赋值的正确方法。

2 个答案:

答案 0 :(得分:4)

问题是虽然你在构造函数中有你的API请求,但它只会在渲染周期后返回一个响应,并且由于你在解析的promise中直接改变状态,所以不会调用重新渲染。

您需要做的是在componentDidMount生命周期方法中调用API并使用setState更新您的状态

constructor(props) {
   super(props);

   this.state = {licensees: []};

}

componentDidMount() {
    LicensingService.getLicensees()
      .then(licensees => {
        this.setState({licensees});
        console.log("component", licensees);
        console.log(licensees[0].city);
    });
}

答案 1 :(得分:1)

首先,您要将api调用移动到componentDidMount而不是在构造函数中执行,这样做不会起作用,因为在获取数据之前,组件已经渲染了。

然后,您需要使用setState来调用渲染函数,以便显示更新的值。像这样:

this.setState({licensees});而不是像

那样直接改变状态
this.state.licensees = licensees;

在此处阅读更多内容Using State Correctly

您还需要等待尝试访问它的值,因此您必须在渲染中进行此更改 而不是:

<td>{this.state.licensees[0].city}</td>

这样做

{this.state.licensees && <td>{this.state.licensees[0].city}</td>} //only render when you have the value in the state.
相关问题