reactjs - 如何强制刷新图像
问题描述
这是我正在处理的一个小项目:https ://codesandbox.io/embed/rwxookx6po 。
我有几个具有backgroundImage
属性的 div。我打的网址是这个:https ://source.unsplash.com/collection/1163637/480x480
每次您访问该网址时,您都会从该集合中获得一个新的随机图像。我认为因为道具没有改变,我可以强制我的组件更新,但这似乎并没有解决问题:
shouldComponentUpdate(nextProps) {
if (nextProps.image) {
this.forceUpdate();
return true;
}
}
假设我按下一个按钮并将相同的图像 url 属性传递给包含带有背景图像的 div 的组件,我怎样才能让组件重新加载,给我的 div 一个新的图像背景?
解决方案
您可以在 updateImage 方法中添加时间戳,如下所示:
updateImage() {
const width = 480;
const height = 480;
const timestamp = Date.now();
const imageURL = `https://source.unsplash.com/collection/1163637/${width}x${height}?t=${timestamp}`;
return this.props.updateImage(imageURL, width, height);
}
推荐阅读
- python - 如何将 keras 自定义指标设置为仅在纪元结束时调用?
- c# - 如何在 .net Core 2.2 中正确创建锚助手
- python-3.x - Python3 x Socket - ICMP Echo 请求 - 为什么我的套接字挂在 recv 上?
- sonata-admin - Sonata-Project 的 Google Authenticator:来自 Application\Sonata\UserBundle\Entity\User 的未定义方法“getTwoStepVerificationCode”
- javascript - BootstrapToggle switch 有条件地切换状态
- elasticsearch - Elasticsearch 索引不尊重模板和映射
- amazon-web-services - 在来自胶水爬虫的 ETL 之后流水线化 Athena 查询
- regex - 如何在VS2017中使用正则表达式从响应头中提取requesttoken?
- jdbc - apache Beam中普通JDBC和JDBCIO连接器的区别?
- python - 使用 Python 请求库时出现错误 10060