【发布时间】: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 文本。回退已从我的本地文件中导入。我会更新帖子以避免混淆。
标签: javascript reactjs rest