我想获取使用 reactJS 15.5
的用户列表,代码:
constructor(props) {
super(props);
this.state = {
values: []
};
this.getDataFromUser = this.getDataFromUser.bind(this);
}
render() {
return (
<div>
<button onClick={this.getDataFromUser}>Fetch</button>
<p>
{this.state.values}
</p>
</div>
);
}
getDataFromUser(){
fetch('http://localhost:8000/api/user')
.then(response => response.json())
.then(json => {
console.log(json);
this.setState({values: json })
})
}
但是当我点击按钮 Fetch 时出现此错误,因此 getDataFromUser 中出现错误:
Unhandled Rejection (Invariant Violation): Objects are not valid as a React child (found: object with keys {id, nom, prenom, email,is_admin,created_at, updated_at}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.
创建用户对象是有原因的,所以任何人都可以帮助我解决这个问题,谢谢
最佳答案
它是一个对象数组,因此您需要使用map
来迭代数组然后呈现特定值。
像这样:
render() {
return (
<div>
<button onClick={this.getDataFromUser}>Fetch</button>
<p>
{this.state.values.map(el => {
return <div key={el.id}>
<span>{el.email}</span>
<span>{el.nom}</span>
<span>{el.is_manager}</span>
</div>
})}
</p>
</div>
);
}
关于javascript - 如何在 ReactJS 中渲染对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154951/