簡體   English   中英

使用React.js渲染API響應

[英]Render API response with React.js

我正在嘗試呈現我創建的簡單api的響應,但是當我嘗試遍歷項目時,它的定義是不確定的。 我知道它與異步編程有關,但無法弄清楚如何解決它。 有人可以幫忙嗎?

 import React from 'react'; export default class Home extends React.Component { constructor(props) { super(props); this.state = { items: undefined }; } componentDidMount() { fetch('https://petzie-cajuhqnpqy.now.sh/breeds') .then(res => res.json()) .then(data => { this.setState(() => { return { items: data.result }; }); console.log(this.state); }) .catch(err => console.log(err)); } render() { return ( <div> { this.state.items.map((item) => { return <p>{item.name}</p>; }) } </div> ); } } 

首先,如果要通過this.state.items進入.map ,則在任何時候都this.state.items定義它,否則會引發錯誤( .map需要一個數組)。 因此,在構造函數中,將其定義為一個空數組:

constructor(props) {
    super(props);
    this.state = { items: [] };
}

其次, setState是異步的。 因此,當您立即調用setStatethis.state時,該對象尚未更新。 但是由於React的性質,每當更新它時,都會再次調用您的渲染函數,這一次this.state.items將從API中獲取數據。

如果您有異步調用,則需要執行以下操作:

render() {
    if(!this.state.items) { 
        return <div></div> 
    }
    return (
        <div>    
            { this.state.items.map((item) => {
                return <p>{item.name}</p>;
            }) }         
        </div>
    );
}

是做到這一點的一種方法。

暫無
暫無

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

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