>目标是访问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>
);
}
}
您需要先从状态中提取myData
,然后再尝试在render()
函数中使用它。您可以使用以下代码行执行此操作: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[0].id
.通过这种方式,您将能够访问列表的第一个对象:
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>
)
}
}
该问题的解决方法是数据类型是返回响应中的字符串。要访问对象中的值,需要将其从字符串转换为对象。JSON.parse() 做到了这个伎俩。