plm*_*k61 5 javascript image reactjs react-dom
我们正在一个项目中使用hydrate,react-dom并且很难检测到损坏的图像链接。这些图像来自第三方API,因此我们无法事先知道哪些链接有效。
export default class Image extends PureComponent {
  render() {
    return (
      <img
        src={this.props.src}
        onError={(e) => {  
          e.target.src='https://mycdn.com/fallback.jpg';
        }}
      />
    )
  }
}
如果我们使用render而不是,上述代码将起作用hydrate。使用时是否有办法检测损坏的图像hydrate?
不幸的是,ReactDOM.hydrate没有附加onLoad或onError事件。
我能想到的最好的方法是进行两遍渲染。从服务器,始终渲染后备(或占位符)图像。在客户端上,使用componentDidMount并声明将图像更新src为真实来源。
export default class Image extends PureComponent {
  state = { isMounted: false }
  componentDidMount() {
    this.setState({ isMounted: true });
  }
  render() {
    return (
      <img
        src={ isMounted ? this.props.src : this.props.fallbackSrc }
        onError={(e) => {  
          e.target.src = this.props.fallbackSrc;
        }}
      />
    );
  }
}
由于服务器不调用componentDidMount生命周期,因此它将始终渲染后备图像。
完成并安装组件后hydrate,它将更新状态,触发重新渲染,然后使用真实的srcfrom 属性。
| 归档时间: | 
 | 
| 查看次数: | 219 次 | 
| 最近记录: |