简体   繁体   English

fetch 返回 404 时替换 img url

[英]Replace img url when fetch returns 404

I need to display a fallback image when the original url request returns with a 404. The image wont return an error until it's called upon and I can't figure out how to access that 404 to redirect it.当原始 url 请求返回 404 时,我需要显示后备图像。该图像在被调用之前不会返回错误,并且我无法弄清楚如何访问该 404 以重定向它。

the fallback image has been imported from my local files后备图像已从我的本地文件导入

My if statement in checkImg = (props) => {} is completely disregarded as it is now.我在checkImg = (props) => {} if 语句现在完全被忽略了。

export default class FirstListPage extends React.Component{

  checkImg = (product) => {
    if(product.imgurl === null){
      return <img src={fallback} alt='default' />                        
    }
    return <img src={product.imgurl} alt='first choice' />
  }

  render(){                
    if (this.props.firstList.data === undefined){
      return null
    }        
    return(
      <div className='card-wrapper'>                        
         {this.props.firstList.data.map(product => 
            <div className='card' 
               key={product.id}>                                                
                 {this.checkImg(product)}                                                
                <h3>{product.title}</h3>
                <p>{product.description}</p>
            </div>
          )}
      </div>
    )                        
  }
}

The only other thing I can think of would be to modify my .catch but I cant wrap my head around how I would specify such a case.我唯一能想到的另一件事是修改我的.catch但我无法确定我将如何指定这种情况。

App.js应用程序.js

 componentDidMount() {         
        Promise.all([
            fetch(`${config.API_ENDPOINT}/first`),
            fetch(`${config.API_ENDPOINT}/second`),
            fetch(`${config.API_ENDPOINT}/third`)
        ])
        .then( ([firstRes, secondRes, thirdRes]) => {
            if (!firstRes.ok) 
                return firstRes.json()
                    .then( e => Promise.reject(e))

            if (!secondRes.ok) 
                return secondRes.json()
                    .then(e => Promise.reject(e))

            if (!thirdRes.ok) 
                return thirdRes.json()
                    .then(e => Promise.reject(e))

            return Promise.all([ firstRes.json(), secondRes.json(), thirdRes.json() ])
        })
        .then(([first, second, third]) => { this.setState({firstList, secondList, thirdList}) })        
        .catch(error => { console.error({error}) }) 
    }

Data example数据示例

  firstList: {
    itemsPerPage: 6,
    pages: 12,
    data: [
      {
        id: 1,
        imgurl:'https://website.com/image.jpg',
        title: 'shoes',
        description: 'desc here'
      },
    ]
  }

Write your custom image component with error handling using onError handler.使用onError处理程序编写带有错误处理的自定义图像组件。

Save is Error into your component state and in case of error show static image static/404.png保存Error到您的组件状态,如果出现错误,则显示静态图像static/404.png

import React from "react";

class ImageComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { imageStatus: "loading", error: false };
  }

  handleImageLoaded() {
    this.setState({ imageStatus: "loaded", error: false });
  }

  handleImageError() {
    this.setState({ imageStatus: "failed to load", error: true });
  }

  render() {
    return (
      <div>
        <img
          src={this.state.error ? 'static/404.png' : this.props.imageUrl}
          onLoad={this.handleImageLoaded.bind(this)}
          onError={this.handleImageError.bind(this)}
        />
        {this.state.imageStatus}
      </div>
    );
  }
}

export default ImageComponent;

You can use onError prop.您可以使用onError道具。 And update the state on onError.并更新 onError 上的状态。

 handleImageError = () => { this.setState({imageSrcExist: false}) } checkImg = (product) => { return <img src={this.state.imageSrcExist ? product.imgurl : fallbackUrl} onError={this.handleImageError} alt='first choice' /> }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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