【问题标题】:Updating Graph on Interval on React在 React 上更新时间间隔图
【发布时间】:2022-02-09 17:24:18
【问题描述】:

我正在从我的数据库中获取数据以将其显示在图表上。目前,我将不得不刷新页面以更新图表。我想以 x 间隔刷新图表,因为我的数据将以 x 间隔插入。我正在使用 ant design 进行绘图。我正在使用“主页”来显示我的图表和另一个用于获取数据的类。

Home.js

export class Home extends Component {
  static displayName = Home.name;

  render () {
    return (
      <div>
        <h1>Dashboard</h1>
        <h2>
        <div className="site-card-wrapper">
    
      Graph1
      <Graph />}

  </div>
        </h2>
      </div>
    );
  }
}

Temp.js

const TempGraph = () => {

 const [data, setData] = useState([]);

  useEffect(() => {
    asyncFetch();
  }, []);

  const asyncFetch = () => {
      fetch('link')
      .then((response) => response.json())
      .then((json) => setDatajson))
      .catch((error) => {
        console.log('fetch data failed', error);
      });
  };
    const config = {
        data,
        xField: 'time',
        yField: 'value',
        seriesField:'location',
        xAxis: {
          title: {
          text: 'Hours',
          }
        },
        yAxis:{
            title:{
            text: 'Temperature in °',
          }
        },
        
        meta: {
          time: {
            alias: 'hours',
    
          },
          value: {
            alias: 'temperature',
            max: 50,
          },
        },
    
      };
     return <Line {...config} />;
}
export default TempGraph;

【问题讨论】:

    标签: reactjs graph antd ant-design-pro


    【解决方案1】:

    您可以在 useEffect 中添加一个 setInterval 来获取数据并再次更新它们。不要忘记清除返回的间隔:

    useEffect(() => {
       const interval = setInterval(() => asyncFetch(), 5000)
       return () => clearInterval(interval)
    }, []}
    

    此示例每 5000ms 触发一次,根据需要更改值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      相关资源
      最近更新 更多