2017-07-27 87 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> 
); 

}