目标是在ReactJS中访问JSON数据中的键和值。
当前此value={this.state.myData}返回以下JSON格式数据:
"list":[
{
"id": "1",
"first_name": "FirstName",
"last_name": "LastName"
},
"address:"{
"street": "123",
"City": "CityName",
"State": "StateName"
},
"other_info": []
]
UI结构:
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>
);
}
}
发布于 2020-06-30 22:43:04
解决此问题的方法是,数据类型是返回响应中的字符串。为了访问对象中的值,需要将其从字符串转换为对象。JSON.parse()做到了这一点。
发布于 2020-04-03 23:03:07
在尝试在render()
函数中使用它之前,您需要从状态中提取myData
。您可以使用下面这行代码来完成此操作: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>
)
}
}
发布于 2020-04-03 23:42:23
因为list是一个数组,所以尝试执行list[0].id
。这样你就可以访问list的第一个对象了:
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>
)
}
}
https://stackoverflow.com/questions/61021553
复制相似问题