Замените img url, когда fetch вернет 404 - PullRequest
0 голосов
/ 15 марта 2020

Мне нужно отобразить запасное изображение, когда исходный URL-запрос возвращается с 404. Изображение не будет возвращать ошибку до тех пор, пока оно не будет вызвано, и я не могу понять, как получить доступ к этому 404, чтобы перенаправить его.

резервное изображение было импортировано из моих локальных файлов

Оператор My if в checkImg = (props) => {} полностью игнорируется, как и сейчас.

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>
    )                        
  }
}

Единственное, о чем я могу подумать, это изменить мой .catch, но я не могу обернуть голову, как бы я указывал такой случай.

Приложение. 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}) }) 
    }

Пример данных

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

Ответы [ 2 ]

1 голос
/ 15 марта 2020

Напишите свой пользовательский компонент изображения с обработкой ошибок, используя обработчик onError.

Сохраните Error в состояние вашего компонента и в случае ошибки покажите stati c image 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;
0 голосов
/ 15 марта 2020

Вы можете использовать onError проп. И обновите состояние на onError.

handleImageError = () => {
this.setState({imageSrcExist: false})
}

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