简体   繁体   English

UseEffect 中的 SetInterval 无延迟

[英]SetInterval in UseEffect without Delay

I am building a movie app in React to practice.我正在用 React 构建一个电影应用程序来练习。

In the homepage there is a big banner with movie poster and information about movies, content of this banner is changing every 5 seconds.主页上有一个带有电影海报和电影信息的大横幅,该横幅的内容每 5 秒更改一次。 I created this function for this:我为此创建了这个 function:

 const [movie, setMovie] = useState('');     //const movie returns object of one random movie

  useEffect(() => {
    async function fetchData() {
      const request = await axios.get(requests.fetchNetflixOriginals);  
      setMovie(
        request.data.results[
          Math.floor(Math.random() * request.data.results.length)
        ]
      );
    }
    const interval = setInterval(() => {
      fetchData();
    }, 5000)
   return () => clearInterval(interval)   
  }, [movie]);

This solution has a problem: there is a 5sec delay when I run this app for the first time (caused by setInterval).这个解决方案有一个问题:我第一次运行这个应用程序时有 5 秒的延迟(由 setInterval 引起)。

So my question is, if there is any solution to get the same behaviour, just without the delay at the start?所以我的问题是,如果有任何解决方案来获得相同的行为,只是在开始时没有延迟?

I tried a lot of different solutions including defining new states, but all of them causes bugs or infinite loop.我尝试了很多不同的解决方案,包括定义新状态,但所有这些都会导致错误或无限循环。

Thanks!谢谢!

Just call fetchData when defining the interval?定义间隔时只需调用fetchData

useEffect(() => {
    async function fetchData() {
        const request = await axios.get(requests.fetchNetflixOriginals);
        setMovie(
            request.data.results[
            Math.floor(Math.random() * request.data.results.length)
            ]
        );
    }
    fetchData();
    const interval = setInterval(fetchData, 5000)
    return () => clearInterval(interval)
}, [movie]);

Yes, I have already tried exactly this solution with invoking function firstly and then setting an interval.是的,我已经尝试过这个解决方案,首先调用 function 然后设置一个间隔。 But the result is that banner starts to have crazy behaviour.但结果是横幅开始有疯狂的行为。 It changes literally 10x in a single second endlessly.它在一秒钟内无休止地改变了 10 倍。

I attach a whole updated component code to be sure I didn't miss something to send:我附上了一个完整的更新组件代码,以确保我没有错过要发送的内容:

const Banner = () => {
  const [movie, setMovie] = useState({});

  useEffect(() => {
    async function fetchData() {
        const request = await axios.get(requests.fetchNetflixOriginals);
        setMovie(
            request.data.results[
            Math.floor(Math.random() * request.data.results.length)
            ]
        );
    }
    fetchData();
    const interval = setInterval(fetchData, 5000)
    return () => {
      clearInterval(interval)
    }
}, [movie]);

  function truncate(str, n) {
    return str?.length > n ? str.substr(0, n - 1) + '...' : str;
  }

  return (
    <header
      className='banner'
      style={{
        backgroundSize: 'cover',
        backgroundImage: `url(https://image.tmdb.org/t/p/original/${movie?.backdrop_path})`, 
        backgroundPosition: 'center center',
      }}
    >
      <div className='banner__contents'>
        <h1 className='banner__title'>
          {movie?.title || movie?.name || movie?.original_name}
        </h1>
        <div className='banner__buttons'>
          <button className='banner__button'>Play</button>
          <button className='banner__button'>My List</button>
        </div>
        <h1 className='banner__description'>
          {truncate(movie?.overview, 120)}
        </h1>
      </div>
      <div className='banner--fadeBottom'></div>
    </header>
  );
};

Any ideas what should caused it/how to prevent from this behaviour?任何想法应该导致它/如何防止这种行为?

I fixed the issue, after adding another useEffect hook.在添加了另一个 useEffect 挂钩后,我解决了这个问题。 But i am not sure if it will call some other issue.但我不确定它是否会调用其他问题。

useEffect(() => { 
  fetchData()
})

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

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