![](/img/trans.png)
[英]How to display json object using *ngFor and access key,value of object
[英]How to access JSON object key and value in ReactJS
目标是从 ReactJS 中的 JSON 数据中访问键和值。
目前此值={this.state.myData} 返回以下 JSON 格式数据:
"list":[
{
"id": "1",
"first_name": "FirstName",
"last_name": "LastName"
},
"address:"{
"street": "123",
"City": "CityName",
"State": "StateName"
},
"other_info": []
]
界面结构:
export default class App extends Component {
contstructor(props) {
super(props);
this.state = {
myData: "",
};
}
render() {
return (
<div className="container">
<table>
<tr>
<th>ID</th>
<td>{myData.id}</td>
</tr>
<tr>
<th>first_name</th>
<td>{myData.first_name}</td>
</tr>
</table>
</div>
);
}
}
您需要先从 state 中提取myData
,然后再尝试在您的render()
function 中使用它。 您可以使用以下代码行来执行此操作: const {myData} = this.state;
. 你也可以做类似const myData = this.state.myData;
import React, {Component} from 'react';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
myData: {
"list": [
{
"id": "1",
"first_name": "FirstName",
"last_name": "LastName",
"address": {
"street": "123",
"City": "CityName",
"State": "StateName"
},
"other_info": []
}]
}
}
};
render() {
// Extract myData from this.state.
const {myData} = this.state;
return(
<div className="container">
<table>
<tr>
<th>ID</th><td>{myData.id}</td>
</tr>
<tr>
<th>first_name</th><td>{myData.first_name}</td>
</tr>
</table>
</div>
)
}
}
由于 list 是一个数组,请尝试执行list[0].id
。 通过这种方式,您将能够访问列表的第一个 object:
import React, {Component} from 'react';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
myData: {
"list": [
{
"id": "1",
"first_name": "FirstName",
"last_name": "LastName",
"address": {
"street": "123",
"City": "CityName",
"State": "StateName"
},
"other_info": []
}
]
}
}
};
render() {
// Do not store this.state in a variable. it's bad coding habits
return(
<div className="container">
<table>
<tr>
<th>ID</th>
<td>{this.state.myData.list[0].id}</td>
</tr>
<tr>
<th>first_name</th>
<td>{this.state.myData.list[0].first_name}</td>
</tr>
</table>
</div>
)
}
}
该问题的修复是数据类型是来自返回响应的字符串。 要访问 object 中的值,需要将其从字符串转换为 object。 JSON.parse() 成功了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.