如何正确显示通过JSON中的URL收到的列表?
以下是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 :(得分:0)
因为您将新闻的初始值定义为字符串,所以将其定义为数组。
像这样写:
[root@ha-node1 ~]# nova service-list
+----+------------------+----------+----------+---------+-------+----------------------------+-----------------+
| Id | Binary | Host | Zone | Status | State | Updated_at | Disabled Reason |
+----+------------------+----------+----------+---------+-------+----------------------------+-----------------+
| 2 | nova-consoleauth | ha-node3 | internal | enabled | up | 2017-07-27T07:36:31.000000 | - |
| 5 | nova-conductor | ha-node3 | internal | enabled | up | 2017-07-27T07:36:30.000000 | - |
| 7 | nova-cert | ha-node3 | internal | enabled | up | 2017-07-27T07:36:31.000000 | - |
| 15 | nova-scheduler | ha-node3 | internal | enabled | up | 2017-07-27T07:36:30.000000 | - |
| 22 | nova-cert | ha-node1 | internal | enabled | up | 2017-07-27T07:36:20.000000 | - |
| 29 | nova-conductor | ha-node1 | internal | enabled | up | 2017-07-27T07:36:21.000000 | - |
| 32 | nova-consoleauth | ha-node1 | internal | enabled | up | 2017-07-27T07:36:23.000000 | - |
| 33 | nova-consoleauth | ha-node2 | internal | enabled | up | 2017-07-27T07:36:24.000000 | - |
| 36 | nova-scheduler | ha-node1 | internal | enabled | up | 2017-07-27T07:36:20.000000 | - |
| 40 | nova-conductor | ha-node2 | internal | enabled | up | 2017-07-27T07:36:22.000000 | - |
| 44 | nova-cert | ha-node2 | internal | enabled | up | 2017-07-27T07:36:30.000000 | - |
| 46 | nova-scheduler | ha-node2 | internal | enabled | up | 2017-07-27T07:36:24.000000 | - |
+----+------------------+----------+----------+---------+-------+----------------------------+-----------------+
fetch将是一个异步调用,你在componentDidMount中获取将在初始渲染后调用,所以在你得到响应之前,你试图在字符串上使用map,这就是抛出错误。 / p>
检查此代码段:
this.state = {
news: [],
....
&#13;
答案 1 :(得分:0)
您没有正确使用地图。 map不支持object literal。需要提供一个阵列。您需要将状态定义为数组并使用以下渲染功能。
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>
);
}