首页 > 解决方案 > 如何在 Reactjs 上运行一个函数并每 5 秒更改一次内容

问题描述

您好,我想知道你们如何在 React js 上每 5 秒运行一个函数

这是代码:

function Home() {

const [quotes,setQuotes] = useState([])

const getQuotes = ()=>{
    axios.get('https://api.kanye.rest')
    .then(res=>{
        const quotes = res.data.quote
        setQuotes(quotes)
    })
}

useEffect(()=>{
    getQuotes()
},[])


return (
    <div className="home-container">
        <p className="pcolor">Here's a random quotes from Kanye:</p>
        <p>{quotes}</p>
    </div>
)}

我想知道如何每 5 秒获取一次数据,所以我会在 jsx 中自动更新。是的,每次我们请求时,kanye api 都会给我们一个随机报价。

标签: reactjsapiaxiosjsxuse-effect

解决方案


// Use a ref to keep track of a stateful value that doesn't affect rendering,
// the `setInterval` ID in this case.
const intervalRef = useRef();
const [quotes, setQuotes] = useState([])

useEffect(() => {
  const getQuotes = () => {
    axios.get('https://api.kanye.rest')
    .then(res=>{
        const quotes = res.data.quote
        setQuotes(quotes)
    })
  }

  intervalRef.current = setInterval(getQuotes, 5000);

  // Clear the interval when this hook/component unmounts so it doesn't keep
  // running when this component is gone.
  return () => {
    clearInterval(intervalRef.current);
  }
}, [])

推荐阅读