【问题标题】:filtering data after fetch for graph获取图表后过滤数据
【发布时间】:2022-01-17 21:31:32
【问题描述】:

我正在使用 API 从数据库中获取数据,这些数据将用于显示在图表中。以下是 API 的格式。我希望我的图表只显示时间而不是时区的日期。有没有办法将值从字符串更改为 int?

API data
[{"time":"2022-01-13T15:26:20.129055+08:00","location":"north","value":"30","sensorType":null,"type":"temperature"},
{"time":"2022-01-13T15:54:31.718588+08:00","location":"north","value":"35","sensorType":null,"type":"temperature"}]
code for fetch and x,y for plotting graph
 const [data, setData] = useState([]);

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

  const asyncFetch = () => {
      fetch('api')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => {
        console.log('fetch data failed', error);
      });
  };
    const config = {
        data,
        xField: 'time',
        yField: 'value',

【问题讨论】:

    标签: reactjs fetch fetch-api


    【解决方案1】:

    您可以根据时间字符串创建Date 对象,并根据需要获取时间。

    尝试如下。

    const apiData = {"time":"2022-01-13T15:26:20.129055+08:00","location":"north","value":"30","sensorType":null,"type":"temperature"};
    
    const timeStamp = new Date(apiData.time);
     
    // int value of time in millis
    console.log(timeStamp.getTime());
    
    // formatted time
    console.log(`${timeStamp.getHours()}:${timeStamp.getMinutes()}`);
    在您的 then 块中更新数据,然后将其设置为 data
    .then((json) =>
        setData(
            (json || []).map((item) => {
                const timeStamp = new Date(item.time);
                return {
                    ...item,
                    time: `${timeStamp.getHours()}:${timeStamp.getMinutes()}`,
                };
            })
        )
    )
    

    【讨论】:

    • 是否可以在配置之前更改数据变量?
    • 是的,我会更新答案!
    • @JJJJJ,更新了答案!您可以在验证后将其标记为答案吗?
    • 我遇到了这个类型错误:data.filter 不是函数。这个错误会出现在我使用的模块上吗?
    • 你能放一个console.log(json)并用它更新问题吗?
    猜你喜欢
    • 1970-01-01
    • 2013-01-17
    • 2012-12-21
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-09
    相关资源
    最近更新 更多