Objects are not valid as a React child (found: [object Promise])(对象作为 React 子级无效(发现:[object Promise]))
问题描述
我正在尝试通过数组映射来呈现帖子列表.我以前做过很多次,但出于某种原因
renderPosts = async() =>{尝试 {让 res = await axios.get('/posts');让帖子= res.data;返回 post.map((post, i) => {返回 (<li key={i} className="list-group-item>>{post.text}</li>);});} 捕捉(错误){控制台日志(错误);}}使成为 () {返回 (<ul className="list-group list-group-flush">{this.renderPosts()}</ul></div>);}我得到的是:
<块引用>未捕获的错误:对象作为 React 子项无效(找到:[object Promise]).如果您打算渲染一组子项,请改用数组.
我检查了从 renderPosts 返回的数据,它是一个具有正确值且没有任何承诺的数组.这是怎么回事?
解决方案 this.renderPosts()
将返回一个 Promise
而不是实际数据,AFAIK Reactjs 不会在 render
中隐式解析 Promise.
你需要这样做
componentDidMount() {this.renderPosts();}renderPosts = async() =>{尝试 {const res = await axios.get('/posts');常量帖子= res.data;//这将使用新数据重新渲染视图这个.setState({帖子:帖子});} 捕捉(错误){控制台日志(错误);}}使成为() {const posts = this.state.Posts?.map((post, i) => (<li key={i} className="list-group-item>>{post.text}</li>));返回 (<ul className="list-group list-group-flush">{帖子}</ul></div>);}I am trying to render a list of posts by mapping through an array. I've done this many times before but for some reason
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.
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?
解决方案 this.renderPosts()
will return a Promise
not the actual data, and AFAIK Reactjs will not resolve Promises implicitly in render
.
You need to do it like this
componentDidMount() {
this.renderPosts();
}
renderPosts = async() => {
try {
const res = await axios.get('/posts');
const posts = res.data;
// this will re render the view with new data
this.setState({
Posts: posts
});
} catch (err) {
console.log(err);
}
}
render() {
const posts = this.state.Posts?.map((post, i) => (
<li key={i} className="list-group-item">{post.text}</li>
));
return (
<div>
<ul className="list-group list-group-flush">
{posts}
</ul>
</div>
);
}
这篇关于对象作为 React 子级无效(发现:[object Promise])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对象作为 React 子级无效(发现:[object Promise])
基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 动态更新多个选择框 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01