当原始 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'
},
]
}
最佳答案
使用 onError
处理程序编写带有错误处理功能的自定义图像组件。
保存错误
到您的组件状态中,如果出现错误,则显示静态图像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;
关于javascript - 当fetch返回404时替换img url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60690843/