You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React图表多线条实现及10秒价格追踪线方案咨询

适合React+Node.js的实时价格追踪线解决方案

以下几个成熟的React图表库都能实现你需要的10-15秒连续价格追踪线效果,结合Node.js可以轻松搭建数据推送和前端可视化流程:

1. 使用react-chartjs-2 + Chart.js

这是轻量级且配置灵活的图表方案,非常适合实时折线图场景:

实现步骤:

  • 安装依赖:
    npm install react-chartjs-2 chart.js
    
  • 前端组件示例(实时绘制10秒价格线):
    import React, { useState, useEffect, useRef } from 'react';
    import { Line } from 'react-chartjs-2';
    import { Chart, registerables } from 'chart.js';
    
    Chart.register(...registerables);
    
    const PriceTracker = () => {
      const [priceData, setPriceData] = useState({
        labels: [],
        datasets: [{
          label: '实时价格',
          data: [],
          borderColor: '#36A2EB',
          tension: 0.1,
          fill: false
        }]
      });
      const timerRef = useRef(null);
      const startTimeRef = useRef(Date.now());
    
      useEffect(() => {
        // 启动定时更新(可替换为Node.js推送的真实数据)
        timerRef.current = setInterval(() => {
          const elapsed = (Date.now() - startTimeRef.current) / 1000;
          if (elapsed > 10) {
            clearInterval(timerRef.current);
            return;
          }
    
          // 模拟价格数据(实际从后端获取)
          const newPrice = Math.random() * 100 + 50;
          setPriceData(prev => ({
            labels: [...prev.labels, elapsed.toFixed(1) + 's'],
            datasets: [{
              ...prev.datasets[0],
              data: [...prev.datasets[0].data, newPrice]
            }]
          }));
        }, 1000);
    
        // 清理定时器避免内存泄漏
        return () => clearInterval(timerRef.current);
      }, []);
    
      return (
        <div style={{ width: '800px', height: '400px' }}>
          <Line data={priceData} options={{
            scales: {
              x: { title: { display: true, text: '时间(秒)' } },
              y: { title: { display: true, text: '价格' } }
            }
          }} />
        </div>
      );
    };
    
    export default PriceTracker;
    

2. 使用Recharts

Recharts基于React和D3,语法更贴合React组件化风格:

实现步骤:

  • 安装依赖:
    npm install recharts
    
  • 前端组件示例:
    import React, { useState, useEffect, useRef } from 'react';
    import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip } from 'recharts';
    
    const PriceTracker = () => {
      const [data, setData] = useState([]);
      const timerRef = useRef(null);
      const startTimeRef = useRef(Date.now());
    
      useEffect(() => {
        timerRef.current = setInterval(() => {
          const elapsed = (Date.now() - startTimeRef.current) / 1000;
          if (elapsed > 10) {
            clearInterval(timerRef.current);
            return;
          }
    
          const newPrice = Math.random() * 100 + 50;
          setData(prev => [...prev, { time: elapsed.toFixed(1) + 's', price: newPrice }]);
        }, 1000);
    
        return () => clearInterval(timerRef.current);
      }, []);
    
      return (
        <LineChart width={800} height={400} data={data}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="time" />
          <YAxis />
          <Tooltip />
          <Line type="monotone" dataKey="price" stroke="#36A2EB" />
        </LineChart>
      );
    };
    
    export default PriceTracker;
    

Node.js端数据推送建议

如果需要从后端获取真实价格数据,推荐用WebSocket(ws库)或Server-Sent Events实现实时推送:

  • WebSocket服务示例:
    // Node.js服务器代码
    const WebSocket = require('ws');
    const wss = new WebSocket.Server({ port: 8080 });
    
    wss.on('connection', (ws) => {
      const interval = setInterval(() => {
        // 模拟生成价格数据,实际从业务数据源获取
        const price = Math.random() * 100 + 50;
        ws.send(JSON.stringify({ price, timestamp: Date.now() }));
      }, 1000);
    
      ws.on('close', () => clearInterval(interval));
    });
    
  • 前端通过WebSocket接收数据,替换示例中的模拟数据即可。

关键注意事项

  • 控制数据范围:只保留最近10秒的价格点,避免图表数据过载影响性能。
  • 组件卸载清理:务必清除定时器和WebSocket连接,防止内存泄漏。
  • 样式自定义:根据UI需求调整图表的颜色、尺寸、坐标轴等配置。

内容的提问来源于stack exchange,提问作者TechnoDeveloper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:15:39