等待功能响应,然后在componentDidUpdate

时间:2018-05-29 08:24:20

标签: javascript image reactjs

我想在componentDidUpdate函数中检查图像是否存在,并返回true或false。

    componentDidUpdate(prevProps){
    if(prevProps.loadedGroup !== this.props.loadedGroup 
        || prevProps.loadedGroupErrors !== this.props.loadedGroupErrors){
            let image = false;
            if(this.props.loadedGroup.picture !== null){
                if(this.props.loadedGroup.picture.fullResolutionPicName !== undefined){
                        //image = true; //have to be true to print image - false showing placeholder
                        image = checkImage(apiPicturesUrl + this.props.loadedGroup.picture.fullResolutionPicName)
                 }
            }

        this.setState({loadedData: this.props.loadedGroup, 
            loadingGroupDataSpinner: false, loadedPosts: this.props.loadedGroup.posts ,
            showBackdrop: false, openEditPlace: false, openEditPlaceDesc: false, 
            bgImageLoadedSucces: image});        
    }
}

我的checImage功能。

function checkImage(src){
var image = new Image(); 
image.src = src;
    if (image.width === 0) {
        alert("no image");
        return false;
    }else{
        return true;
    }
}

有一个问题,因为该功能是异步执行的,当我检查img宽度时,即使有图像也没有更新到目前为止。

如何在没有setTimeout的情况下正确编写?

1 个答案:

答案 0 :(得分:0)

很快 - 使用image.onload事件。



// Replace this code
image = checkImage(apiPicturesUrl + this.props.loadedGroup.picture.fullResolutionPicName)

// with
image = new Image();
image.onload = () => this.setState({
// here you can be sure, that image is loaded, and set components state with data you need
});
image.src = apiPicturesUrl + this.props.loadedGroup.picture.fullResolutionPicName;

// Note, that it is important to have `onload` and `src` lines be written right in this order.
// First you register event handler, then you set the `src`