从JSON对象数据设置状态时反应16中出现错误。

时间:2018-07-13 07:21:25

标签: reactjs

从JSON对象数据设置状态时反应16中出错。结果

这是错误

x ←→ 1 of 2 errors on the page
Objects are not valid as a React child (found: object with keys {gender, name, location, email, login, dob, registered, phone, cell, id, picture, nat}). If you meant to render a collection of children, use an array instead.
    in div (at App.js:47)
    in App (at index.js:7)

这是代码

componentDidMount()
{
  fetch('https://randomuser.me/api/?results=50').then(results=>{
    return results.json().then(data => {
      this.setState(
      {
        pictures : data.results
      });
      console.log(data.results);
    });


  });

2 个答案:

答案 0 :(得分:0)

我认为您错误地返回了响应json。应该是这样的:

var self = this;
fetch('https://randomuser.me/api/?results=50', {
 responseType: 'json',
})
.then((response) => response.json())
.then((json) => {
    console.log(json.data)
    self.setState({pictures : json.data },()=>{
       console.log(self.state.pictures)
    })
});

答案 1 :(得分:0)

Objects are not valid as a React child

此错误表示,您将普通js对象返回为child,这是不允许的。您必须对其进行映射,并加上一些标记。不幸的是,您没有提供该组件的完整源代码。

我认为实际错误在您的render()方法内。

相关问题