Reactjs 强制重新加载图像文件?
我的React应用程序允许用户上传个人资料图像。这是通过将图像上传到AmazonS3存储桶,并将图像路径以及图像上传的日期和时间存储在我的数据库中来完成的。图像的文件名设置为用户的ID 当用户上传新图像时,我遇到了一个问题。由于图像路径相同,React不知道有任何更改,这意味着我必须刷新页面才能看到更改 由于我有一个日期字段,我可以使用componentWillReceiveProps来知道何时上传了新图像。以下console.log确实在正确的时间触发:Reactjs 强制重新加载图像文件?,reactjs,Reactjs,我的React应用程序允许用户上传个人资料图像。这是通过将图像上传到AmazonS3存储桶,并将图像路径以及图像上传的日期和时间存储在我的数据库中来完成的。图像的文件名设置为用户的ID 当用户上传新图像时,我遇到了一个问题。由于图像路径相同,React不知道有任何更改,这意味着我必须刷新页面才能看到更改 由于我有一个日期字段,我可以使用componentWillReceiveProps来知道何时上传了新图像。以下console.log确实在正确的时间触发: componentWillReceiv
componentWillReceiveProps(nextProps) {
if (this.state.picDate.getTime() !== nextProps.user.pic.date.getTime()) {
console.log('image date has changed');
// this.forceUpdate();
}
}
我可以用它来重新渲染图像吗?我尝试了
这个.forceUpdate()
,但没有成功。我想这是因为浏览器缓存。尝试在更改图像URL后添加一些散列,如date.now()
。例如:
setState({
imageSrc: '...',
imageHash: Date.now()
})
在渲染中:
render(){
return(
<img src={`${imageSrc}?${imageHash}`} />
)
}
render(){
返回(
)
}
您可以尝试执行类似以下操作:首先将状态设置为null,这样图像就不会显示,然后再次将状态设置为具有路径的特定图像
constructor(props){
super(props);
this.state = {
image_path : 'before update image path'
};
}
componentWillReceiveProps(nextProps) {
if (this.state.picDate.getTime() !== nextProps.user.pic.date.getTime()) {
console.log('image date has changed');
//now here set state
this.setState({
image_path : 'your new image path or older as you explained both are same' + '?' + Math.random()
});
}
}
这对我来说很好
<img src={`${props.src}?${new Date().getTime()}`} />
只需将图像路径设置为空,然后设置为您的路径,react将假定其已更改,并将加载新图片
this.setState({image_path : ''});
this.setState({image_path : 'Actual Image Source'});
就像我在文件上传
功能中所做的那样
this.setState({userimage:''});
this.setState({userimage:"http://localhost:5000/auth/getProfilePic/" + this.state.username,});
我在当地的形象上遇到了这个问题。正在修改图像,但URL保持不变 诀窍就是向图像添加一个在图像更改时更改的键属性。例如:
<Image key={Date.now()} source={{uri: <your local uri>}/>
(Eric Wiener答案的增强),在上传到s3时设置键(即时间戳),以获得更清晰的刷新
const [timestamp, setTimestamp] = React.useState(Date.now());
axios.post("/api/upload/s3", formData)
.then(res => {
setTimestamp(Date.now())
})
<Avatar key={timestamp} className={classes.avatar} src={user_info.avatar} onClick={handleOpenPicture}></Avatar>
const[timestamp,setTimestamp]=React.useState(Date.now());
axios.post(“/api/upload/s3”,formData)
。然后(res=>{
setTimestamp(Date.now())
})
将当前日期作为查询参数添加到图像url
<img src={`${image_url}?${global.Date.now()}`} />
为什么用新的键渲染img
不起作用?我以为这会重新创建dom元素?(这不是缓存-在网络开发工具选项卡中根本没有显示任何请求)好的建议,我也犯了同样的错误。事实上,我的状态是正常的,但缓存没有更新我的图像源。谢谢。@olejorgenb同样的问题。实际上,一开始我想到了更新的密钥的方法,但是没有更新。我想这不是关于DOM,而是关于浏览器资产,cachI发现这比公认的解决方案更干净。在我的例子中,我无法更改img
src属性,因为它是一个远程URL.welcome。谢谢加入stackoverflow。只是一个小小的建议,就是解释这个解决方案的原因和工作方式也非常类似于公认的答案,因此确保使用新的价值,即使是通过在“原因:”中更具体地说明它。)