【问题标题】:Replace img url when fetch returns 404fetch 返回 404 时替换 img url
【发布时间】:2020-03-15 16:37:39
【问题描述】:

当原始 url 请求返回 404 时,我需要显示后备图像。图像在被调用之前不会返回错误,并且我 无法弄清楚如何访问该 404 以重定向它。

后备图片已从我的本地文件中导入

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

我能想到的唯一另一件事是修改我的.catch,但我无法理解如何指定这种情况。

App.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'
      },
    ]
  }

【问题讨论】:

  • 如果图片没有 URL,响应会是什么样子?
  • checkImg 函数中,您正在使用src={fallback} 后备来自哪里?
  • 所有图片都会有 url,有些会被破坏并在控制台中返回 404,并呈现 alt 文本。回退已从我的本地文件中导入。我会更新帖子以避免混淆。
  • thisthis中接受的答案

标签: javascript reactjs rest


【解决方案1】:

使用onError 处理程序编写带有错误处理的自定义图像组件。

将 isError 保存到您的组件状态中,如果出现错误,请显示静态图像 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;

【讨论】:

    【解决方案2】:

    你可以使用onError 属性。并更新 onError 上的状态。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 2018-12-16
      • 2019-12-03
      • 2017-05-24
      • 1970-01-01
      • 2021-11-04
      相关资源
      最近更新 更多