我有一个 React + Rails 应用程序,当前的 S3 服务器问题让我意识到,当无法从 s3 提取数据时,我没有适当的回退机制。目前我正在尝试让它与我本地存储的图像一起使用,并且我计划以相同的方式将其添加到我的其他图像标签中。
我的img
如下:
errorLink() {
this.onError = null;
this.src = '/img/icons/static/credentials.svg';
}
<img alt="Icon for credentials and experience" src="/img/icons/static/credentials123.svg" onError={this.errorLink.bind(this)()}/>
图像内指向credentials123.svg
的src
是一个虚拟的,我专门添加它来引发错误。但它没有更新我的图像的 src 。我怎样才能在 react 中实现这一目标?我不想在下次亚马逊中断期间向我的用户显示损坏的图像链接
最佳答案
众多解决方案之一(因为它实际上基于您内部的 React 项目结构)。您只需将图像网址保留为默认图像即可。从 S3 获取正确的图像 URL 后,您将使用获得的新图像替换状态中的默认图像 URL。
const DEFAULT_IMAGE = '/img/icons/static/default.svg';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
url: DEFAULT_IMAGE
};
}
render() {
return (
{/* ... some UI here ... */}
<img
alt="Icon for credentials and experience"
src={this.state.url}
/>
);
}
// ....
_someAsync = () => {
// some async logic here
// In here in 5 seconds state will be updated by replacing default url
// with new url image link
setTimeout(() => this.setState({
loaded: true,
url: '/img/icons/static/credentials.svg'
}), 5000);
};
}
关于javascript - 在服务器失败期间将后备 src 添加到 React 上的图像 (S3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42518323/