简体   繁体   English

当 src 更改时,React img 不会立即更改。 我怎样才能解决这个问题?

[英]React img not immediately changing when src changes. How can I fix this?

I have a basic <img> with a src.我有一个带有 src 的基本<img>

<img src={src} />

If I change the src from say /1.jpg to /2.jpg and the new image takes 1 second to load, React will continue to show /1.jpg until the new image is loaded.如果我将 src 从/1.jpg/2.jpg并且新图像需要 1 秒才能加载,React 将继续显示/1.jpg直到加载新图像。

What I want is for the old image to be discarded while the new image is being loaded.我想要的是在加载新图像时丢弃旧图像。 (eg display: none) (例如显示:无)

Any idea how to accomplish this?知道如何做到这一点吗? Ideally without conditional rendering, because I still need to use onLoad and onError理想情况下没有条件渲染,因为我仍然需要使用onLoadonError

EDIT: Here's some more code.编辑:这里还有一些代码。 It's a little more complicated than my question, but I'm just trying to add some loading and error state to the image.这比我的问题要复杂一点,但我只是想为图像添加一些加载和错误状态。

I have a button that calls this onClick我有一个按钮调用这个 onClick

this.props.history.push('/${page + 1}');

This is the image component, where src is based on the page from the URL.这是图像组件,其中 src 基于来自 URL 的page

import React, { Component } from 'react';
import CenteredLoading from 'components/loading/CenteredLoading';

type Props = { src: string };

type State = {
  status: 'LOADING' | 'LOADED' | 'FAILED',
};

class ImageWithLoader extends Component<Props, State> {
  state = {
    status: 'LOADING',
  };

  handleImageLoad = () => {
    this.setState({ status: 'LOADED' });
    console.error('image loaded');
  };

  handleImageError = () => {
    this.setState({ status: 'FAILED' });
    console.error('image error');
  };

  render() {
    const { src, ...otherProps } = this.props;
    const { status } = this.state;

    return (
      <React.Fragment>
        <img
        {...otherProps}
        onLoad={this.handleImageLoad}
        onError={this.handleImageError}
        src={src}
        />

        {status === 'LOADING' && <CenteredLoading />}
        {status === 'FAILED' && <p>error</p>}
      </React.Fragment>
    );
  }
}

export default ImageWithLoader;

只需将关键属性添加到您的图像标签,并为图像源等关键属性分配一些唯一值。

<img src={image_source} key={image_source}></img>

Made my own workaround.做了我自己的解决方法。

I believe because react isn't mounting a new component (ie <img> ), it's not going to update to the new image until it's finished loading.我相信因为 react 没有安装新组件(即<img> ),所以在加载完成之前它不会更新到新图像。

What I did was check if the src changed in componentDidUpdate and change the status to LOADING .我所做的是检查srccomponentDidUpdate更改并将状态更改为LOADING Then I set img style to display: none while its status was LOADING .然后我将 img 样式设置为display: none而其状态为LOADING

EDIT: Also, by manually setting my own key, I can force React to re-render the <img>编辑:另外,通过手动设置我自己的密钥,我可以强制 React 重新渲染<img>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM