Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/454.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ';错误:对象作为React子对象无效(找到:具有键{results,info})和#x27;_Javascript_Reactjs - Fatal编程技术网

Javascript ';错误:对象作为React子对象无效(找到:具有键{results,info})和#x27;

Javascript ';错误:对象作为React子对象无效(找到:具有键{results,info})和#x27;,javascript,reactjs,Javascript,Reactjs,使用fetch i react时,出现以下错误“错误:对象作为react子对象无效(找到:具有键{results,info}的对象)” 这是我的密码 import React from "react"; import "./App.css"; class App extends React.Component { constructor() { super(); this.state = { data: [],

使用fetch i react时,出现以下错误“错误:对象作为react子对象无效(找到:具有键{results,info}的对象)”

这是我的密码

    import React from "react";
import "./App.css";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [],
      IsLoding: false,
    };
  }

  componentDidMount() {
    fetch("https://api.randomuser.me/")
      .then(response => response.json())
      .then(data => this.setState({
        data: data,
        IsLoding: true
      }));[enter image description here][1]
  }

  render() {
    return (
      <div>
        <h1>
          Hello
          {this.state.data}
        </h1>
      </div>
    );
  }
}

export default App;
<pre>{JSON.stringify(this.state.data, null, 4)}</pre>
从“React”导入React;
导入“/App.css”;
类应用程序扩展了React.Component{
构造函数(){
超级();
此.state={
数据:[],
岛民:错,
};
}
componentDidMount(){
取回(“https://api.randomuser.me/")
.then(response=>response.json())
.然后(数据=>this.setState({
数据:数据,
岛民:对
}));[在此处输入图像描述][1]
}
render(){
返回(
你好
{this.state.data}
);
}
}
导出默认应用程序;
错误 [1] :


当尝试Consle.log(数据)时,它正在工作,但当尝试将数据获取到不工作的页面时,您需要映射数据,因为您无法渲染对象

例如,如果您只想看到性别,请尝试以下方法:

{this.state.data.results.map(item => <p>{item.gender}</p>)} 
{this.state.data.results.map(item=>{item.gender}

)}
或者您可以实现一个呈现用户信息的用户组件

{this.state.data.results.map(item => <User item={item}} />)}
{this.state.data.results.map(item=>)}
在映射数组时不要忘记添加关键道具


此.state.data
使用对象
{results,info}
填充,从那里您只能呈现字符串或数字属性,例如

对于数组
[]
,您需要映射它们

{this.state.data.results.map(result => result.gender)} 
在这种情况下,结果是一个对象数组,
map
将逐个获取并将其存储在变量result中,这将是一个对象

对于对象
{}
,需要找到要渲染的属性

{this.state.data.info.results}
现在,如果您希望渲染整个对象,则需要将其转换为如下字符串

{JSON.stringify(this.state.data,null,4)}

API返回的以及您在控制台中看到的
数据是什么。(我们看不到您的控制台输出。)只有当它是一个简单的字符串(或这些字符串的数组)时,您的
渲染才会工作,但从错误来看,它似乎是一个对象。这是否回答了您的问题?这是API,它应该返回名称和性别,并且在console@Ahmed,检查上面的问题。不能渲染整个对象,应使用属性。