【问题标题】:How do I conditionally render a spinner while waiting for a new image to load?如何在等待新图像加载时有条件地渲染微调器?
【发布时间】:2020-03-04 05:47:17
【问题描述】:

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

我尝试向 Photo 组件添加 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>
  );
}

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

【问题讨论】:

    标签: javascript reactjs event-handling


    【解决方案1】:

    添加一个isLoading 状态并在您的useEffect 中设置/取消设置它:

      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 (
        <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>
      );
    

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 2017-10-29
      • 2020-11-23
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多