我正在从服务中获取这样的 Json 对象
{"0":{"UserID":1,"Gender":"F","Age":1,"Occupation":10,"Zip-code":48067},
"1":{"UserID":2,"Gender":"M","Age":56,"Occupation":16,"Zip-code":70072},
"2":{"UserID":3,"Gender":"M","Age":25,"Occupation":15,"Zip-code":55117},
"3":{"UserID":4,"Gender":"M","Age":45,"Occupation":7,"Zip-code":2460},"4":}
然后使用 React 我尝试将其映射到一个状态,但它是一个对象而不是对象数组
class App extends Component {
constructor() {
super();
this.state = {
users: []
}
}
componentDidMount() {
this.getUsers();
};
getUsers() {
axios.get(`${SERVICE_URL}/users`)
.then((res) => {
console.log(res.data); // I can see the data in the console
this.setState({ users: res.data.map((data) => {return (data.key, data.value)} }); })
.catch((err) => { console.log(err); });
}
我虽然这样的东西可能会起作用,但不行。
this.setState({ users: res.data.ToArray().map((data) => {return (data.key, data.value)})})})
最终更新,这就是有效的。 (可能仍然是更干净的方式,但这有效)
class App extends Component {
constructor() {
super();
this.state = {
users: []
}
}
componentDidMount() {
this.getUsers();
};
getUsers() {
axios.get(`${SERVICE_URL}/users`)
.then((res) => {
this.setState({ users: Object.values(JSON.parse(res.data))});
})
.catch((err) => { console.log(err); });
}
render() {
return (
<div>
<table class='userList'>
<tr>
<td>UserId</td>
<td>Gender</td>
<td>Age</td>
<td>Occupation</td>
</tr>
{this.state.users.map(({UserID, Gender, Age, Occupation}) => {
return (
<tr key={'user'+UserID}>
<td> { UserID } </td>
<td> { Gender } </td>
<td> { Age } </td>
<td> { Occupation } </td>
</tr>
)})}
</table>
</div>
);
}
}
export default App;
最佳答案
尝试使用 JSON.parse(res) 解析它,然后您可以像设置状态一样映射数组
关于javascript - 如何使用 React 从 json 对象创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50861312/