【问题标题】:Using React.js Axios to update data results使用 React.js Axios 更新数据结果
【发布时间】:2020-07-23 01:32:07
【问题描述】:

我将 ReactJS 用作带有 JSX 的 javascript 库,并且我正在使用 axios 获取数据。接收到的数据必须每 5 秒重新采集一次。最有效和最好的方法是什么?

我正在考虑使用 setInterval(),但不确定该方法应该放在哪里。

import React, { useState, useEffect } from 'react';
import axios from 'axios'
import './App.css';

const App = () => {
  const [results, setResults] = useState([])

  useEffect(()=>{
     axios.get('API LINK')
        .then(res => {
          setResults(res.data.result)
        });
  },[]);

  const Results = () => {
    return (
      <ul>
        {results.map( (i)=>(<li key={i.sys_id}><h1>{i.u_dashboard}</h1> 
        Calls in Queue (CIQ): {i.u_calls_in_queue}
        {"\n"}Longest Active Call (LAC): {i.u_longest_active_call}</li>)) }
      </ul>
    )
  }

【问题讨论】:

    标签: javascript reactjs api axios jsx


    【解决方案1】:

    你应该在useEffect中使用setInterval,并清除它应该在useEffect中返回的间隔,因为一旦组件卸载就会触发返回。

    useEffect(()=>{
         ...
    
        const interval = setInterval(() => {
    
        axios.get('API LINK')
            .then(res => {
              setResults(res.data.result)
            });
    
        console.log('Every 5 seconds');
        }, 5000);
    
       return () => clearInterval(interval);
    
      },[]);
    
    

    【讨论】:

      【解决方案2】:

      您可以将获取请求放在一个函数中,以便在某个时间间隔内调用

      useEffect(() => {
        const fetchData = () => {
          axios.get('API LINK')
            .then(res => {
              setResults(res.data.result)
            });
        };
      
        fetchData(); // <-- invoke on mount too!
        const timerId = setInterval(fetchData, 5000);
      
        return () => clearInterval(timerId); // <-- return cleanup function
      },[]);
      

      这会在组件卸载时处理取消间隔回调,但不会取消任何正在进行的请求。

      axios cancellation

      useEffect(() => {
        const CancelToken = axios.CancelToken;
        const source = CancelToken.source();
      
        const fetchData = () => {
          axios.get(
            'API LINK',
            {
              cancelToken: source.token,
            },
          )
            .then(res => {
              setResults(res.data.result)
            });
        };
      
        fetchData();
        const timerId = setInterval(fetchData, 5000);
      
        return () => {
          source.cancel();
          clearInterval(timerId);
        };
      },[]);
      

      【讨论】:

        猜你喜欢
        • 2021-05-28
        • 2019-06-27
        • 1970-01-01
        • 2020-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-25
        相关资源
        最近更新 更多