如何在等待新图像加载时有条件地渲染微调器?

How do I conditionally render a spinner while waiting for a new image to load?

我正在编写一个简单的 React 应用程序,它显示来自 NASA API 的 "photo of the day"。我添加了一个日期输入,允许用户选择不同的先前日期并显示这些日期的照片。由于图像有时非常大,我想先显示一个微调器,直到图像完全加载后再显示。

我尝试向照片组件添加 isLoaded 状态,然后在等待图像加载时有条件地渲染微调器。我的想法是,当 img onLoad 触发时,我将 isLoaded 更改为 true 并渲染图像。它似乎并没有真正起作用。

// App.js
function App() {
  const [pod, setPod] = useState({});
  const [date, setDate] = useState(today);

  const handleDateChange = e => {
    setDate(e.target.value);
  };

  useEffect(() => {
    axios
      .get(`${nasa_api}&date=${date}`)
      .then(res => {
        console.log(res.data);
        setPod(res.data);
      })
      .catch(err => {
        console.error(err);
      });
  }, [date]);

  return (
    <div className="App">
      {Object.entries(pod).length ? (
        <>
          <Photo title={pod.title} date={date} url={pod.url} />
          <DatePicker date={date} handleDateChange={handleDateChange} />
          <Explanation explanation={pod.explanation} />
          <Footer copyright={pod.copyright} />
        </>
      ) : (
        <ReactLoading
          className="spinner"
          type="spin"
          color="blue"
          height="5%"
          width="5%"
        />
      )}
    </div>
  );
}
// Photo.js
function Photo(props) {
  return (
    <div className="photo">
      <h1>{props.title}</h1>
      <h3>Date: {props.date}</h3>
      <img src={props.url} alt="NASA Photo of the Day" />
    </div>
  );
}

我希望每次更改日期时都显示一个微调器,直到图像加载完毕,然后才能显示图像。我该怎么做?

在您的 useEffect:

中添加 isLoading 状态和 set/unset
  const [isLoading, setIsLoading] = useState(false)

  // ... //

  useEffect(() => {
    setIsLoading(true)
    axios
      .get(`${nasa_api}&date=${date}`)
      .then(res => {
        console.log(res.data);
        setPod(res.data);
      })
      .catch(err => {
        console.error(err);
      }).then(()=>{
         setIsLoading(false)
      });
  }, [date]);

然后在您的 return:

中使用它
  return (
    <div className="App">
      {!isLoading && Object.entries(pod).length ? (
        <>
          <Photo title={pod.title} date={date} url={pod.url} />
          <DatePicker date={date} handleDateChange={handleDateChange} />
          <Explanation explanation={pod.explanation} />
          <Footer copyright={pod.copyright} />
        </>
      ) : (
        <ReactLoading
          className="spinner"
          type="spin"
          color="blue"
          height="5%"
          width="5%"
        />
      )}
    </div>
  );