简体   繁体   中英

React update state if image not found.

I can't seem to wrap my head around this problem. What I'm trying to do is have React attempt to verify an image is not returning a 404 to display an alternative image instead. Something like the below does not work as React does not wait for the image to attempt to load for returning the component.

getInitialState: function () {
        var img = new Image();
        img.onerror = function() {
            img.src = "alternativeImage.jpg"
        },
        img.src = this.props.image;
        return {image: <img src={img.src} />};
    },

The above code will display the images just fine but the 404 alternative image does not show up.

I've tried to place this in another method outside of getInitialState. I've also tried to have it call an external method outside of the React component, but nothing works.

There is a short hand method of adding onerror attribute on the image tag itself, but it seems React has the same issue of not executing that code and or updating itself based on the outcome.

I think the most frustrating part is that I cannot seem to have any function called that React would be able to work with from the JavaScript image object.

Thanks for any help you can provide.

It's a bad habit to put components into state. What you probably want is something like the following:

var Img = React.createClass({

    componentDidMount: function () {

        var self = this;
        var img = new Image();
        img.onerror = function () {
            self.setState({ src: 'http://i.imgur.com/lL3LtFD.jpg' });
        };

        img.src = this.state.src;

    },

    getInitialState: function () {    
      return { src: '/404.jpg' };
    },

    render: function () {
        return <img src={this.state.src} />;
    }

});

jsfiddle link: http://jsfiddle.net/e2e00wgu

Here's a solution that I came up with. Pretty new to React and programming in general so take this with a grain of salt....

const DEFAULT_IMAGE="http://i.imgur.com/lL3LtFD.jpg"

<img src={this.props.SRC} onError={(e)=>{e.target.src=DEFAULT_IMG}}/>

WARNING: If the default constant is invalid, the browser will be caught in an infinite loop (at least when I tested this in Chrome). I haven't found a solution to this yet, but in vanilla javascript, you set the onerror attribute to null which tells the browser to make only a single request for the asset.
jQuery/JavaScript to replace broken images

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM