gpt4 book ai didi

json - 在react中使用map方法渲染JSON API

转载 作者:行者123 更新时间:2023-12-03 13:31:14 28 4
gpt4 key购买 nike

我在 JSON 对象/数组和映射方法的语法和结构方面遇到困难。我是 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>
);
}

最佳答案

之前的答案几乎是正确的,正确修复提取将解决问题。

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>
);
}

关于json - 在react中使用map方法渲染JSON API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48250294/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com