Bha*_*wna 6 json jsx ecmascript-6 reactjs
我对 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%"
}
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
到目前为止,这是我的代码:我想使用 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>
);
}
Run Code Online (Sandbox Code Playgroud)
前面的答案几乎是正确的,正确修复 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>
);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30205 次 |
最近记录: |