我在条件渲染时遇到问题,我正在向jsonplaceholder发出get请求,并通过setState将结果存储在状态中,因为我遍历每个对象并将结果渲染到浏览器,出现此错误:“渲染未返回任何内容。这通常意味着缺少return语句。或者,要渲染任何内容,请返回null。”
这是该代码段:
从jsonplaceholder获取结果
state = {
people: []
};
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/users").then(response => {
this.setState({ people: response.data });
});
}
在屏幕上显示
render() {
if (this.state.people) {
this.state.people.map(person => {
return (
<React.Fragment>
<h1>{person.name}</h1>
<h2>{person.username}</h2>
<p>{person.email}</p>
</React.Fragment>
);
});
} else {
return null;
}
}
答案 0 :(得分:1)
您需要返回由.map函数创建的结果,该函数是一个数组。
render() {
if (this.state.people) {
return <>
{this.state.people.map(person =>
<React.Fragment>
<h1>{person.name}</h1>
<h2>{person.username}</h2>
<p>{person.email}</p>
</React.Fragment>
)}
</>
} else {
return null;
}
}
答案 1 :(得分:0)
一个空数组is considered truthy in javascript(尝试在控制台中运行!![]
)。因此,当您的组件以空数组作为初始状态装入时,渲染函数将不返回任何内容。
如果将if(this.state.people)
替换为if(this.state.people.length > 0)
,则应该获得预期的行为。