开发者问题收集

每 2 秒从后端刷新一次 React 应用的数据

2021-10-30
971

如何每 2 秒刷新一次我的 React 应用程序?

import React, {useState, useEffect} from 'react';
import {Route, Switch, useLocation} from 'react-router-dom';
import Home from './Home';

function App() {
    const location = useLocation();
    console.log(location);
    const [feedbacks, setFeedbacks] = useState([]);

    useEffect(() => {
        const fetchArticles = async () => {
            setFeedbacks([]);

            const url = 'https://url.abc.com/';
            const api_response = await fetch(url);
            let data = await api_response.json();

            setFeedbacks(data);
        }

        fetchArticles();
    }, [])

    const data = {feedbacks};

    return (
        <div className="App">
            <Switch>
                <Route path="/" render={() => <Home data={data}/>} exact/>
                <Route path="/:username" render={() => <Home data={data}/>} exact/>
            </Switch>
        </div>
    );
}

export default App;
3个回答

您是否尝试过在 fetchArticles 上使用 setInterval(); ?类似这样的代码:

setInterval(fetchArticles(), 2000)
estin8
2021-10-30

有一个用于间隔的 JS 函数“setInterval”,以毫秒为单位的固定间隔运行您传递的函数。

这应该有效:

const fetchArticles = async () => {
    setFeedbacks([]);
    const url = 'https://url.abc.com/';
    const api_response = await fetch(url);
    let data = await api_response.json();
    setFeedbacks(data);
}

useEffect(() => {
    setInterval(fetchArticles(), 2000)
}, [])
Woohaik
2021-10-30
 useEffect(() => {

 const fetchArticles = async () => {
   setFeedbacks([]);
   const url = 'https://url.abc.com/';
   const api_response = await fetch(url);
   let data = await api_response.json();
   setFeedbacks(data);
 }

       setInterval(fetchArticles(), 2000)
 }, [])
Ali Safari
2021-10-30