我在JSON对象/数组和map方法的语法和结构方面遇到了困难。我是React的新手并且处于学习的初始阶段。
这是我粘贴在下面的JSON文件代码:
[
{
"cloud":"Asia",
"availability":{
"last15Min":"100%",
"last24Hour":"100%"
},
"data_centers":[
{
"title":"Bombay",
"availability":{
"last15Min":"100%",
"last24Hour":"100%"
}
},
{
"title":"Bombay1",
"availability":{
"last15Min":"100%",
"last24Hour":"100%"
}
}
]
},
{
"cloud":"Europe",
"availability":{
"last15Min":"100%",
"last24Hour":"100%"
},
"data_centers":[
{
"title": "Bombay",
"availability": {
"last15Min": "100%",
"last24Hour": "100%"
}
},
{
"title":"Bombay1",
"availability":{
"last15Min":"100%",
"last24Hour":"100%"
}
}
]
}
]
到目前为止,这是我的代码:我想使用map方法渲染每个字段。 这样做的正确方法是什么?
在componentDidMount中,我在console.log中收到响应 http://prntscr.com/i09rqt
constructor(props) {
super(props)
this.state = {
clouds:[]
}
}
componentDidMount() {
var url="<api url>";
fetch(url)
.then(response => {
return response.json();
}).then(d => {
let clouds = d.map((cloudData)=>{
return(
<div>{cloudData}</div>
)
})
this.setState({clouds: clouds});
console.log("state", this.state.clouds)
})
}
render() {
return (
<div>
{
this.state.clouds.map((cloud =>
<th key="">
{cloud}
</th>
))
}
</div>
);
}
答案 0 :(得分:2)
无需在html
内返回componentDidMount
元素。
试试这个:
constructor(props) {
super(props)
this.state = {
clouds: []
}
}
componentDidMount() {
var url = "http://trust.zscaler.com.test/sample-api/third-party-monitoring/availability.json";
fetch(url)
.then(response => {
this.setState({ clouds : response })
}).catch(error => {
console.log(error)
})
}
render() {
if (this.state.clouds && this.state.clouds.length > 0) {
return (
<div>
{
this.state.clouds.map((items =>
<th key="">
{items.cloud}
</th>
))
}
</div>
);
}
return null;
}
希望这会对你有所帮助。
答案 1 :(得分:1)
以前的答案几乎是正确的,正确修复fetch将解决问题。
componentDidMount() {
var url = "https://demo8192935.mockable.io/mockApi";
fetch(url)
.then(response => {
return response.json();
})
.then(d => {
this.setState({ clouds: d });
console.log("state", this.state.clouds)
})
.catch(error => console.log(error))
}
render() {
return (
<div>
{
this.state.clouds.map(((cloud, index) =>
<th key={`${cloud.cloud}${index}`}>
<div>
<div>
{cloud.cloud}
<div>
{
cloud.data_centers.map(d => (
<div>
{d.title}
</div>
))
}
</div>
</div>
</div>
</th>
))
}
</div>
);
}