我的React应用程序允许用户上传个人资料图片.这是通过将图像上传到Amazon S3存储桶并将路径存储到数据库中的图像以及图像上载的日期和时间来完成的.图像的文件名设置为用户的ID.
我在用户上传新图片时遇到问题.由于图像路径相同,React不知道有什么变化,这意味着我必须刷新页面才能看到变化.
由于我有一个日期字段,我可以使用componentWillReceiveProps来了解何时上传了新图像.以下console.log会在正确的时间触发:
componentWillReceiveProps(nextProps) {
if (this.state.picDate.getTime() !== nextProps.user.pic.date.getTime()) {
console.log('image date has changed');
// this.forceUpdate();
}
}
Run Code Online (Sandbox Code Playgroud)
我可以用它来重新渲染图像吗?我试过this.forceUpdate()但它不起作用.
Ema*_*ami 15
我认为这是因为浏览器缓存.尝试添加一些哈希,如date.now()图像URL更改后.例如:
setState({
imageSrc: '...',
imageHash: Date.now()
})
Run Code Online (Sandbox Code Playgroud)
并在渲染:
render(){
return(
<img src={`${imageSrc}?${imageHash}`} />
)
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ner 13
我在本地图像上遇到了这个问题。图像正在修改,但 URL 保持不变。
诀窍是向图像添加一个关键属性,该属性会在图像更改时更改。例如:
<Image key={Date.now()} source={{uri: <your local uri>}/>
Run Code Online (Sandbox Code Playgroud)
它对我来说工作得很好。
<img src={`${props.src}?${new Date().getTime()}`} />
Run Code Online (Sandbox Code Playgroud)
您可以尝试执行一些操作,例如首先将状态设置为空,以便图像不会显示,然后再次将状态设置为带有路径的特定图像。
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()
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5859 次 |
| 最近记录: |