Image onError Handling in React

前端 未结 1 462
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 04:31

I am trying to grab the maxresdefault of multiple YouTube thumbnails. Some YouTube videos simply don\'t have a high res thumbnail photo so I want to catch that with

1条回答
  •  余生分开走
    2021-01-25 04:45

    To achieve this, I would suggest rendering the based on the state of your component.

    You could for instance, create an Image object, attempt to load the background image and by this, reliably determine if the image fails to load. On the images success or failure to load, you would then setState() on your component with the appropriate background value which would instead be used to rendering you actual element:

    class FeaturedVideo extends Component {
    
      componentDidMount() {
    
        if(this.props.background) {
    
          // When component mounts, create an image object and attempt to load background
          fetch(this.props.background).then(response => {
             if(response.ok) {
               // On success, set the background state from background
               // prop
               this.setState({ background : this.props.background })
             } else {        
               // On failure to load, set the "default" background state
               this.setState({ background : this.props.background.replace("maxresdefault", "hqdefault") })
             }
          });
        }
      }
    
      // Update the function signature to be class method to make state access eaiser
      renderVideo(props) {
    
        return 
    {/* Update image src to come from state */}

    WATCH

    {props.title}

    } render() { return (
    {this.renderVideo(this.props)}
    ) } }

    Hope that helps!

    0 讨论(0)
提交回复
热议问题