【发布时间】:2021-04-19 18:44:52
【问题描述】:
有一个代码,在里面我通过数据创建链接并放入一个数组中:
function Blogs(props) {
const links = [];
props.ids.forEach(id => {
fetch(`${root}/api/blog/${id}`)
.then(res => res.json())
.then(res => {
const link = <Link to={`/blog/${id}`}>{_.get(res, 'blog.name', '')}</Link>
links.push(link);
})
});
console.log(links.length) // 0
return (
<div className="profile-blogs">
<div className="a">Блоги</div>
<div className="b">
{links} {/* nothing */}
</div>
</div>
);
}
当我安慰links:
为什么是links.length === 0 以及如何解决它?
【问题讨论】:
-
fetch()是异步。.then()函数将在 HTTP 请求完成时运行。 -
您的
console.log写在之后fetch但实际上fetch是之后调用 因为它需要时间来获取.. . 所以代码移动到console.log,而fetch代码仍在等待数据。这是一个简化的解释。 -
你需要看this。
标签: javascript reactjs lodash