簡體   English   中英

未定義的React JS變量

[英]undefined React JS variable

這是我第一次使用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})是將值分配給狀態對象的正確方法。

問題是,盡管您的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);
    });
}

首先,您希望將api調用移至componentDidMount而不是在構造函數中進行,這樣做將無法工作,因為在獲取數據之前您的組件已經渲染過。

然后,您需要使用setState導致調用渲染函數,以便顯示更新的值。 像這樣 :

this.setState({licensees}); 而不是像直接改變狀態一樣

this.state.licensees = licensees;

在此處閱讀更多內容正確使用狀態

您還需要等待該值,直到嘗試訪問它為止,因此您也必須在渲染中進行此更改,而不是這樣做:

<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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM