Javascript 如何在reactjs中重复获取和呈现更新的api数据?

Javascript 如何在reactjs中重复获取和呈现更新的api数据?,javascript,reactjs,react-router,fetch,dom-events,Javascript,Reactjs,React Router,Fetch,Dom Events,我正在尝试从API端点渲染时间数据 “currentFileTime”属性不断变化,但在加载时呈现一次。 我尝试了setInterval方法来更新状态,但它不起作用。可能是我弄错了 这是App.js: import React , { Component } from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state

我正在尝试从API端点渲染时间数据 “currentFileTime”属性不断变化,但在加载时呈现一次。 我尝试了setInterval方法来更新状态,但它不起作用。可能是我弄错了

这是App.js:

import React , { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { data: []};
  }

 async componentDidMount(){  
                            this.fetchData();      
                          }

  async fetchData() {
    try { 
          const response = await  fetch('http://worldclockapi.com/api/json/utc/now');
          if (!response.ok) {throw Error(response.statusText);}
          const json = await response.json();
          this.setState({ data: json});
          console.log(json);
        }   
    catch (error) {console.log(error);}
  }

  render() {return (<div><h1>worldclockapi.com data (edit App.js)</h1>
                         <li>currentFileTime: {this.state.data.currentFileTime }</li>
              </div> );
            }
}

export default App;
import React,{Component}来自'React';
导入“/App.css”;
类应用程序扩展组件{
建造师(道具){
超级(道具);
this.state={data:[]};
}
异步组件didmount(){
这是fetchData();
}
异步获取数据(){
试试{
const response=等待获取('http://worldclockapi.com/api/json/utc/now');
如果(!response.ok){抛出错误(response.statusText);}
const json=await response.json();
this.setState({data:json});
log(json);
}   
catch(错误){console.log(错误);}
}
render(){return(worldclockapi.com数据(编辑App.js)
  • currentFileTime:{this.state.data.currentFileTime}
  • ); } } 导出默认应用程序;

    如何在react组件中连续呈现和更新currentFileTime?

    这是使用新的挂钩。这应该可以解决问题

    import React, {useEffect, useState} from 'react';
    
    import logo from './logo.svg';
    import './App.css';
    
    const App  = () => {
    const [state, setState] = useState({data: []});
    
    useEffect(()=>{
        fetchData();
    }, [state]);
    
    const fetchData =  async () => {
        try {
            const response = await  fetch('http://worldclockapi.com/api/json/utc/now');
            if (!response.ok) {throw Error(response.statusText);}
            const json = await response.json();
            setState({ data: json});
            console.log(json);
        }
        catch (error) {console.log(error);}
    }
    
    return (<div><h1>worldclockapi.com data (edit App.js)</h1>
    <li>currentFileTime: {state.data.currentFileTime }</li>
    </div> );
    }
    
    export default App;
    
    import React,{useffect,useState}来自“React”;
    从“/logo.svg”导入徽标;
    导入“/App.css”;
    常量应用=()=>{
    const[state,setState]=useState({data:[]});
    useffect(()=>{
    fetchData();
    },[州];
    const fetchData=async()=>{
    试一试{
    const response=等待获取('http://worldclockapi.com/api/json/utc/now');
    如果(!response.ok){抛出错误(response.statusText);}
    const json=await response.json();
    setState({data:json});
    log(json);
    }
    catch(错误){console.log(错误);}
    }
    返回(worldclockapi.com数据(编辑App.js)
    
  • currentFileTime:{state.data.currentFileTime}
  • ); } 导出默认应用程序;
    在成功检索数据后,尝试递归调用fecthData,如下所示。 您不需要将“async”放在componentDidMount前面,因为您不需要在方法调用中等待任何东西

      async fetchData() {
        try { 
              const response = await  fetch('http://worldclockapi.com/api/json/utc/now');
              if (!response.ok) {throw Error(response.statusText);}
              const json = await response.json();
              this.setState({ data: json});
              console.log(json);
    
              // set the time below to how frequently you wanna update 
              setTimeout(() => this.fetchData(), 5000);
              //
            }   
        catch (error) {console.log(error);}
      }
    

    问题是componentDidMount仅在第一次装入组件后执行一次,例如,如果您的状态发生变化,componentDidMount将不会再次执行。 在您的情况下,我认为最好使用WebSocket,但如果您想继续使用此api,可以使用useEffect挂钩,如下所示:

    const [temp, setTemp] = useState(0)
    
    useEffect(()=>{
      setIterval(()=>{
        setTemp((prevTemp)=>prevTemp+1)
      }, 2000)
    }, [])
    
    useEffect(()=>{
      fetchData()
    }, [temp])
    
    在上面的代码中,我们有一个temp变量,它的值每2秒更新一次,每次更新它时,运行第二个useffect,数据将被获取,因此状态将发生变化,元素将被更新