我有以下函数来检查服务器上是否存在图像(头像)。如果是,则显示头像。如果没有,则显示默认头像。
export const Avatar = props => {
const userId = props.userId
const size = props.size ? props.size : 25
fetch(URL.Avatar + '/' + userId + '_avatar.jpg').then(res => {
if (res.status === 404) {
return (
<Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
width: size,
height: size,
borderRadius: size / 2
}} />
)
} else {
return (
<Image source={{uri: URL.Avatar + '/' + userId + '_avatar.jpg' }} style={{
width: size,
height: size,
borderRadius: size / 2
}} />
)
}
}).catch(err => {
return (
<Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
width: size,
height: size,
borderRadius: size / 2
}} />
)
})
}
但是,这个功能不起作用。我收到错误“渲染没有返回任何内容”,因为该函数认为缺少返回语句(最后)。但是,当我将一些 console.logs 放入其中时,获取本身正在工作。 URL 是正确的,因为当我在图像组件末尾添加一个回车符时,它就可以工作。
有人知道问题出在哪里吗?与异步有什么关系吗?
最佳答案
Fetch 是异步的,返回时间将晚于您的预期,因为在 fetch 等待响应时代码将继续运行。
您可以通过等待
获取并使函数异步
来解决此问题
export const Avatar = async props => {
const userId = props.userId
const size = props.size ? props.size : 25
return await fetch(URL.Avatar + '/' + userId + '_avatar.jpg').then(res => {
if (res.status === 404) {
return (
<Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
width: size,
height: size,
borderRadius: size / 2
}} />
)
} else {
return (
<Image source={{uri: URL.Avatar + '/' + userId + '_avatar.jpg' }} style={{
width: size,
height: size,
borderRadius: size / 2
}} />
)
}
}).catch(err => {
return (
<Image source={{uri: URL.Avatar + '/default.jpg' }} style={{
width: size,
height: size,
borderRadius: size / 2
}} />
)
})
}
关于javascript - 使用 fetch 检查图像是否存在(函数不返回响应),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60320219/