我想通过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”,位置:“ california”,性别:“ male”,…}长度:2__proto __:Array(0)


提前致谢

最佳答案

您没有正确设置状态以响应您的API调用,您需要编写this.setState({user: users})而不是this.setState({user: u})

componentDidMount() {
      fetch('/api/get/all').then((res)=>{
        return res.json();
      }).then(users =>{
          this.setState({
            user: users
          })
      });
      // console.log(this.state.user);  <-- This won't show update state since setState is asynchronous
  }


注意:
您可以查看有关setState being asynchronous的更多详细信息的答案

关于javascript - 如何通过javascript中的json对象进行映射?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49893244/

10-17 02:56