Javascript 对象作为 React 子对象无效(找到:[object Promise])
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47658765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objects are not valid as a React child (found: [object Promise])
提问by Aaron
I am trying to render a list of posts by mapping through an array. I've done this many times before but for some
我正在尝试通过数组映射来呈现帖子列表。我以前做过很多次但有些
renderPosts = async () => {
try {
let res = await axios.get('/posts');
let posts = res.data;
return posts.map((post, i) => {
return (
<li key={i} className="list-group-item">{post.text}</li>
);
});
} catch (err) {
console.log(err);
}
}
render () {
return (
<div>
<ul className="list-group list-group-flush">
{this.renderPosts()}
</ul>
</div>
);
}
All I get is:
我得到的是:
Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
未捕获的错误:对象作为 React 子对象无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组。
I've checked the data returned from renderPosts and it is an array with the correct values and no promises. What's going on here?
我检查了从 renderPosts 返回的数据,它是一个具有正确值且没有承诺的数组。这里发生了什么?
回答by Ja9ad335h
this.renderPosts()will return a Promisenot the actual data, and AFAIK Reactjs will not resolve Promises implicitly in render.
this.renderPosts()将返回一个Promise不是实际数据,AFAIK Reactjs 不会在render.
You need to do it like this
你需要这样做
componentDidMount() {
this.renderPosts();
}
renderPosts = async() => {
try {
let res = await axios.get('/posts');
let posts = res.data;
// this will re render the view with new data
this.setState({
Posts: posts.map((post, i) => (
<li key={i} className="list-group-item">{post.text}</li>
))
});
} catch (err) {
console.log(err);
}
}
render() {
return (
<div>
<ul className="list-group list-group-flush">
{this.state.Posts}
</ul>
</div>
);
}
回答by Padhraic
I also received the same error message when creating an async functional component. Functional components should not be async.
在创建异步功能组件时,我也收到了相同的错误消息。功能组件不应该是异步的。
const HelloApp = async (props) => { //<<== removing async here fixed the issue
return (
<div>
<h2>Hello World</h2>
</div>
)
}
ReactDOM.render(<HelloApp />, document.querySelector("#app"))

