gpt4 book ai didi

javascript - 如何使用 React 从 json 对象创建列表

转载 作者:行者123 更新时间:2023-11-29 17:44:38 25 4
gpt4 key购买 nike

我从服务中获取这样的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com