当我使用fetch时,我会收到此错误消息:“错误:对象作为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;
错误 [1]:https://i.stack.imgur.com/klKKP.jpg
当尝试Consle.log(data)正常工作时,但是尝试将数据获取到页面不正常
答案 0 :(得分:0)
您需要映射数据,因为您无法渲染对象。
例如,如果您只想查看性别,请尝试以下操作:
{this.state.data.results.map(item => <p>{item.gender}</p>)}
或者您可以实现呈现用户信息的用户组件
{this.state.data.results.map(item => <User item={item}} />)}
映射数组时不要忘记添加关键道具!
答案 1 :(得分:0)
this.state.data
中填充了一个对象{results, info}
,从那里您只能渲染字符串或数字的属性,例如一些示例
对于数组[]
,您需要对其进行映射
{this.state.data.results.map(result => result.gender)}
在这种情况下,结果是一个对象数组,map
将得到一个对象,并将其存储在变量 result 中,这将是一个对象
对于对象{}
,您需要找到要渲染的属性
{this.state.data.info.results}
现在,如果要渲染整个对象,则需要将其转换为这样的字符串
<pre>{JSON.stringify(this.state.data, null, 4)}</pre>