[英]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
So I am learning React and very basic full stack web development and I keep hitting this promise when I am trying to get an array of objects in my Mongodb.所以我正在学习 React 和非常基本的全栈 Web 开发,当我试图在我的 Mongodb 中获取一组对象时,我一直在兑现这个承诺。 Through Postman I know it is returning what I want [{},{},...].
通过 Postman,我知道它正在返回我想要的东西 [{},{},...]。 But when I try to use it in my component to map the names I keep getting
但是当我尝试在我的组件中使用它来映射我不断得到的名称时
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.
On my web console my list is displaying as a Promise but with the array I want inside of it.在我的网络控制台上,我的列表显示为一个 Promise,但里面有我想要的数组。 I keep trying different setups with my promise, like many posts on here say, to get it to resolve but everything I've tried does not change this outcome.
我一直在用我的承诺尝试不同的设置,就像这里的许多帖子说的那样,以解决它,但我尝试过的一切都不会改变这个结果。
const ArticlesListPage = async () => {
let testResult = function()
{
return fetch('/api/articles-list').then(result => {return result});
};
let results = testResult();
results.then(function(res){
console.log(res.json());
})
}
export default ArticlesListPage;
And the component:和组件:
const ArticlesList = ({articles}) => (
<>
{articles.map((article, key) => (
<Link className="article-list-item" key={key} to={`/article/${article.name}`}>
<h3>{article.title}</h3>
<p>{article.content[0].substring(0,150)}...</p>
</Link>
))}
</>
);
export default ArticlesList;```
This is because you are returning a Promise
and a React Component
can only return JSX.这是因为您正在返回
Promise
而React Component
只能返回 JSX。 Refer to this issue for detailed info:有关详细信息,请参阅此问题:
Why does putting a div tag allow this React code to compile? 为什么放置一个 div 标签允许这个 React 代码编译?
Here is the part thats wrong, the fetch returning:这是错误的部分,获取返回:
return fetch('/api/articles-list').then(result => {return result});
The page (because is a React Component
) cannot return a fetch
该页面(因为是一个
React Component
)不能返回一个fetch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.