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

标签 javascript reactjs ecmascript-6 es6-promise

在我的 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/

相关文章:

javascript - 在reactjs中使用按钮创建显示和隐藏部分

javascript - ECMAScript 6 和 ECMAScript Harmony 有什么区别?

javascript - ES6 Map 和 WeakMap 有什么区别?

javascript - 如何将 JavaScript 字符串转换为对象

javascript - 获取 "TypeError: $(...).css(...) is undefined"尽管使用 if 语句过滤掉所有未定义

unit-testing - 如何使用 sinon 对 localStorage 进行单元测试

javascript - 为什么在 Node JS 中使用 'require' 导入时特殊字符会被替换?

javascript - 使用链接打开对象标签中的内容

javascript - 参数 '' 不是函数,在 Kendo ( AngularJS ) 中未定义

reactjs - Flatlist onEndReached 无限循环