【发布时间】:2018-09-28 07:32:32
【问题描述】:
我想通过 JSON 对象的每个属性映射(循环)。 JSON 看起来像这样
[
{
"_id": "5ad5c0ccdec0fa2b3c1f1ba0",
"name": "optioin",
"job": "google",
"location": "usa",
"gender": "male",
"__v": 0
},
{
"_id": "5ad6043f9fba4125b467c6af",
"name": "reactjs",
"job": "facebook",
"location": "california",
"gender": "male",
"__v": 0
}
]
我希望将此 JSON 分配给我的 reactjs 状态 我的组件看起来像这样
componentDidMount() {
fetch('/api/get/all').then((res)=>{
return res.json();
}).then(users =>{
this.setState({
user: users
})
});
console.log(this.state.user);
}
我已将我的用户状态初始化为
this.state={user:[]};
API 正在像这样从节点服务器响应
app.get('/api/get/all',(req,res)=>{
User.find({},(err,data) => {
// res.json("inside this");
if (err) {
// console.error(err);
res.json({
message:"error"
});
}
// console.log(data.toArray);
res.json(data);
});
});
我想获取每个 JSON 对象的每个值 我的映射函数
<div className="row">
{this.state.user.map(u =>{
<UserDiv name={u.name} age={u.age} location={u.location} gender={u.gender} job={u.job} />
})}
</div>
我得到的错误是
this.state.user.map is not a function
console.log(this.state.user) 的结果
(2) [{…}, {…}]0:{_id:“5ad5c0ccdec0fa2b3c1f1ba0”,名称:“optioin”,工作:“pubg”,位置:“美国”,性别:“男性”,...} 1:{_id:“5ad6043f9fba4125b467c6af”,名称:“reactjs”,工作:“facebook”,位置:“加利福尼亚”,性别:“男性”,......}长度:2__proto__:数组(0)
提前致谢
【问题讨论】:
-
您的
componentDidMount方法中似乎有错字。也许你想做user: users而不是user: u -
this.setState({ user: u })可能你想用this.setState({ user: users }) -
是的,有一个拼写错误,但我用
users也做到了......仍然没有希望
标签: javascript json reactjs