我有我的组件InputAvatar一个问题 - https://codesandbox.io/s/721n5346x6
我怎么可能会显示错误消息后选择照片,如果照片的大小不是200×200像素?
我认为这个问题是img.onload =()函数,因为没有及时返回的错误信息。
谢谢你提前
你说得对,该onload
没有及时返回。这是一个异步事件回调,所以它使用的图像加载完毕之后。这导致从getErrors
返回一个空数组值,因为它是比图像负载更快执行。
为了使代码的工作,你就必须引进一些异步数据的相关代码,例如。使用的承诺。
getErrors(value = this.state.file || "") {
// Return a single promise and move the function execution inside.
return new Promise((resolve, reject) => {
const errors = []
const img = new Image();
img.src = value;
img.onload = function() {
var w = img.width;
var h = img.height;
errors.push("error");
if (w != 200 || h != 200) {
errors.push("The photo must be 200 x 200 px.");
}
// Resolve the pending promise with the errors value letting callers know it's ready.
resolve(errors)
};
})
}
这样,你就可以等待图像加载的成果,并在你需要它的方式使用它。
validate(value = this.state.file || "") {
this.getErrors(value)
// Wait for the errors and only then set the state.
.then(errors =>
this.setState({
errors
});
)
}