使用 hydrate 而不是 react-dom 渲染时检测损坏的图像

Detect broken image when using hydrate instead of render from react-dom

我们正在项目中使用 react-dom 中的 hydrate,并且很难检测到损坏的图像链接。这些图像来自第 3 方 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 没有附加 onLoadonError 事件。

我能想到的最好的方法是进行一种 2-pass 渲染。在服务器中,始终呈现后备(或占位符)图像。在客户端,使用 componentDidMount 和 state 将图像的 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 完成并安装组件后,它将更新触发重新渲染的状态,然后使用道具中的真实 src