gpt4 book ai didi

javascript - JS/React - 函数在完成前返回未定义

转载 作者:行者123 更新时间:2023-11-30 09:29:08 24 4
gpt4 key购买 nike

在我的 React 应用程序中,我创建了一个函数来从数组中获取特定图像大小,该数组包含有关图像的数据,例如 mimetype、可用大小、路径等。

export default function getImageSize(image, size) {

// Map through each available size for the image
image.sizes.forEach((v, i) => {

// Return the fullpath if there is a match for the requested size
if (v.type === size) {
return v.fullpath;
}

});

}

我正在调用这个函数:

let smallImageSize = getImageSize(data.images[0], 'small');

并在我的页面中使用它:

<img alt="thumbnail" src={smallImageSize} />

您可能会猜到(对于更有经验的人),我的函数返回未定义,因为函数内部的循环在函数完成之前尚未返回。

我的问题是,如何确保我的函数在我的渲染函数中的任何其他内容继续之前等待返回值?使用 promise 是唯一的方法吗?

感谢您的帮助。

最佳答案

问题出在您的 forEach 循环中。从 forEach 循环返回一个值实际上并没有做任何事情。

您需要改用find:

export default function getImageSize(image, size) {

// Map through each available size for the image
const img = image.sizes.find(v => {

// Return the image if there is a match for the requested size
if (v.type === size) {
return true;
}

});

// img can be undefined if it does not exist
return img && img.fullpath;
}

关于javascript - JS/React - 函数在完成前返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47446442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com