【问题标题】:JS / React - Function returns undefined before finishedJS / React - 函数在完成之前返回未定义
【发布时间】:2017-11-23 01:55:17
【问题描述】:

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

正如您可能猜到的那样(对于更有经验的人),我的函数返回 undefined,因为函数内部的循环在函数完成之前没有返回。

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

感谢您的帮助。

【问题讨论】:

  • 我也刚刚有了一个想法:在页面呈现在componentWillMount之前使用这个函数并通过状态加载URL会更好吗?我在 React 的 render() 中运行这个函数。
  • 你应该使用const foundSize = image.sizes.find(imageSize =&gt; imageSize.type === size); return foundSize &amp;&amp; foundSize.fullpath;而不是forEach。
  • 另外,我们需要知道data.images[0]是什么。
  • 其实getImageSize函数在整个事情完成后返回undefined,所以标题是错误的——es6-promise标签是没有根据的

标签: javascript reactjs ecmascript-6 es6-promise


【解决方案1】:

问题在于您的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 库中添加 find() 并在将来使用它。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
  • 1970-01-01
  • 1970-01-01
  • 2014-07-10
  • 2020-09-26
  • 2015-02-17
相关资源
最近更新 更多