2017-07-27 78 views
0

如何正確地顯示列表通過URL收到JSON?如何顯示列表?

這裏是一個project的一個例子。如果我使用局部變量 - 一切正常,如果我得到列表,它會顯示一個錯誤。

constructor(props) { 
    super(props); 
    this.urlNews = "https://api.myjson.com/bins/1nrbo"; 
    this.state = { 
     news: "", 
     links: [ 
     { 
      name: "Имя 1", 
      url: "http://localhost:1", 
      use: true 
     }, 
     { 
      name: "Имя 2", 
      url: "http://localhost:2", 
      use: false 
     }, 
     { 
      name: "Имя 3", 
      url: "http://localhost:3", 
      use: false 
     } 
     ] 
    }; 
    } 
    getNews() { 
    fetch(this.urlNews) 
     .then(response => { 
     return response.json(); 
     }) 
     .then(json => { 
     this.setState({ 
      news: json 
     }); 
     console.log(this.state.news[1]); 
     }); 
    } 
    componentDidMount() { 
    this.getNews(); 
    } 
    render() { 
    const { news } = this.state; 
    return (
     <ul> 
     {news.map((item, index) => <li>1</li>)} 
     </ul> 
    ); 
    } 

怎麼回事?

+0

而且它顯示什麼樣的錯誤?當你在這裏尋求幫助時,你應該總是這樣說。 – Meier

回答

0

因爲你定義的消息的初始值作爲,將它定義爲一個陣列。

寫這樣的:

this.state = { 
    news: [], 
    .... 

獲取將是一個異步調用,你是取在componentDidMount,將最初的渲染之後被調用,所以你得到的迴應之前,你想上使用地圖字符串,這是拋出錯誤。

檢查這個片段:

let news = ''; 
 

 
news.map(el => { 
 
    console.log(el); 
 
})

0

您沒有使用正確的地圖。地圖不支持對象字面量。需要提供一個數組。您需要將狀態定義爲數組並使用以下渲染函數。

this.state = { 
    news: [], 
    links: [ 
    { 
     name: "Имя 1", 
     url: "http://localhost:1", 
     use: true 
    }, 
    { 
     name: "Имя 2", 
     url: "http://localhost:2", 
     use: false 
    }, 
    { 
     name: "Имя 3", 
     url: "http://localhost:3", 
     use: false 
    } 
    ] 
}; 

以下渲染函數有效。

render() { 
return (
    <ul> 
    {this.state.news.map(() => <li>1</li>)} 
    </ul> 
); 

}