反应滑块防止图像在更改时重新加载

react slider prevent image reload on change

我正在使用 React 和 运行 制作图像滑块,但出现了从远程重新请求图像的问题 URL

这里有一个 JS Fiddle 说明了这个问题:https://jsfiddle.net/iioinc/sz8pf245/

当我第一次打开图片滑块并转到下一张幻灯片时,会加载第一张和第二张图片。然后,当我转到上一张幻灯片时,第一张图片再次加载。这在每次幻灯片更改时都会继续 - 从同一遥控器再次请求图像 URLs:

这是代码

import React, { useState } from "react";
import ReactDOM from "react-dom";

const slideImages = [
  "https://images.pexels.com/photos/189349/pexels-photo-189349.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260",
  "https://images.pexels.com/photos/585759/pexels-photo-585759.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
];

const Slider = (props) => {
  const [currentIndex, setCurrentIndex] = useState(1);

  const onNavNext = () => {
    const nextIndex =
      currentIndex === slideImages.length - 1 ? 0 : currentIndex + 1;

    setCurrentIndex(nextIndex);
  };

  const onNavPrev = () => {
    const nextIndex =
      currentIndex === 0 ? slideImages.length - 1 : currentIndex - 1;

    setCurrentIndex(nextIndex);
  };

  return (
    <div>
      <p onClick={onNavPrev}>Prev</p>
      <div className="slider-container">
        <img className="slide" src={slideImages[currentIndex]} />
      </div>
      <p onClick={onNavNext}>Next</p>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Slider />, rootElement);

JS Fiddle: https://jsfiddle.net/iioinc/sz8pf245/

我在这里看到一个相关问题:

但它没有用,因为我认为这是一个不同的场景 - HTML 正在被替换,所以 memoize 没有帮助

如何防止每次更换幻灯片时重新加载图像?获取相同的数据是一种浪费,对于大图像,用户每次都可以看到图像重新加载

由于您在 Devtools - 网络中打开了“禁用缓存”选项,因此重新加载了图像。关闭此选项将解决您的问题。