【发布时间】: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 => imageSize.type === size); return foundSize && foundSize.fullpath;而不是forEach。 -
另外,我们需要知道
data.images[0]是什么。 -
其实
getImageSize函数在整个事情完成后返回undefined,所以标题是错误的——es6-promise标签是没有根据的
标签: javascript reactjs ecmascript-6 es6-promise