2017-04-24 38 views
2

我有一個包含標題,描述和圖像URL屬性的10個對象(讓我們稱之爲「博客」)的數組。我需要在HTML標籤中包裝每個屬性並將它們全部導出,以便它們全部加載到網頁上。React set對象數組的狀態

使用我當前的代碼,我只獲得當前狀態中的一個對象加載到頁面上。我如何獲得處於相同狀態的所有對象?

class NewBlogs extends React.Component { 
    constructor(props) { 
     this.state = { 
      title: [], 
      description: [], 
      image: [], 
      loading: true 
     }; 
    } 
    componentDidMount() { 
     axios.get('/new-blogs').then(data => { 
      const blogs = data.data; 
      var component = this; 

       for(var i in blogs) { 
        component.setState({ 
         title: blogs[i].title, 
         description: blogs[i].description, 
         image: blogs[i].image, 
         loading: false 
        }); 
       } 
      }) 
      .catch(function(error) { 
       console.log(error); 
      }); 
     } 
     render() { 
      return (
       <div> 
        <h2>New Blogs:</h2> 
        <h3>{this.state.title}</h3> 
        <em>{this.state.description}</em> 
        <img src={this.state.image}></img> 
       </div> 
      ); 
     } 
    } 
    export default NewBlogs 

回答

5

我沒有運行/測試這一點,但嘗試這樣的事情

的API調用似乎返回對象的列表。如果是這樣,只需在xhr完成後設置狀態並將加載設置爲false一次。

在反應render()是你可以迭代你的列表。最簡單的方法是使用'.map()'。然後您只需爲列表中的每個對象返回反應元素。

也讓我們重新命名 '組件' 到 '清單'

class NewBlogs extends React.Component { 
 
    constructor(props) { 
 
     this.state = { 
 
      list: [], 
 
      loading: true 
 
     }; 
 
    } 
 
    componentDidMount() { 
 
     axios.get('/new-blogs').then(data => { 
 
      // const blogs = data.data; 
 
      // var component = this; 
 
      this.setState({list: data.data, loading: false }) 
 
       // for(var i in blogs) { 
 
       //  this.setState({ 
 
       //   title: blogs[i].title, 
 
       //   description: blogs[i].description, 
 
       //   image: blogs[i].image, 
 
       //   loading: false 
 
       //  }); 
 
       // } 
 
      }) 
 
      .catch(function(error) { 
 
       console.log(error); 
 
      }); 
 
     } 
 
     render() { 
 
      return (
 
       <div> 
 
        {this.state.list.map(e => (
 
         <h2>New Blogs:</h2> 
 
         <h3>{e.title}</h3> 
 
         <em>{e.description}</em> 
 
         <img src={e.image}></img> 
 
        ))} 
 
        
 
       </div> 
 
      ); 
 
     } 
 
    } 
 
    export default NewBlogs

+0

謝謝。這使我找到了正確的方向。我收到一個錯誤:「TypeError:無法將未定義或null轉換爲Function.keys()上的對象」。我將繼續玩明天的代碼和調試。當我得到它時,我會標記爲正確的。 – Rick

+0

我可以證實這個作品。謝謝。 – Rick