首页 > 解决方案 > 如何将动态数据加载到 react-native-chart-kit?

问题描述

实际上,我会动态地将数据加载到react-native-chart-kit,但我找不到任何关于如何做到这一点的文档。

我有一个 API,它提供每个月的数据,其中有一些收入,响应如下所示

[{"IMPORTO":722.51},{"IMPORTO":911},{"IMPORTO":1188.53},{"IMPORTO":12},{"IMPORTO":390.65},{"IMPORTO":54.98}]

我还有一种方法可以获取该数据,但我不知道如何将其用作图表的数据集。

这是我构建图表的 Home.JS 的代码,GetData 是 API DATA 的获取函数:

  import React from 'react';
import {Text,View,Dimensions} from 'react-native';
import {LineChart} from "react-native-chart-kit";

const data = {
  labels: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
  datasets: [
    {
      data: []
    }
  ]
}
const chartConfig = {
  backgroundColor: "#e26a00",
  backgroundGradientFrom: "#fb8c00",
  backgroundGradientTo: "#ffa726",
  decimalPlaces: 2, // optional, defaults to 2dp
  color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
  labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
  style: {
    borderRadius: 16
  },
  propsForDots: {
    r: "6",
    strokeWidth: "2",
    stroke: "#ffa726"
  }
}

export default class Home extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      isLoading: true,
      dataSource: []
    };

  }

  componentDidMount() {
  this.GetData();
  }

  GetData = () => {
    return fetch('http://192.168.100.158:3000/data')
    .then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson
      });
    })
    .catch((error) =>{
      console.error(error);
    });
  }

  render() {
    data.datasets[0].data = this.state.dataSource.map(value => value. IMPORTO);

    return (
      <View>
      <LineChart
      data={data}
      width={Dimensions.get("window").width} // from react-native
      height={220}
      yAxisLabel={"$"}
      chartConfig={chartConfig}
      bezier
      style={{
        marginVertical: 8,
        borderRadius: 16
      }}
      />
      </View>
    );
  }
}

我尝试设置 data = { this.state.dataSource.IMPORTO } 但它不起作用。

标签: javascriptreactjsreact-native

解决方案


在您的渲染方法中,将数据更改为来自状态。

render() {

    data.datasets[0].data = this.state.dataSource.map(value => value.IMPORTO);

    return (
      <View>
          <LineChart
              data={data}
              width={Dimensions.get("window").width} // from react-native
              height={220}
              yAxisLabel={"$"}
              chartConfig={chartConfig}
              bezier
              style={{
                    marginVertical: 8,
                    borderRadius: 16
              }}
          />
      </View>
    );
}

现在,当异步调用“GetData()”完成时,它将更新状态,并且组件将使用新数据重新渲染。

您还可以在状态本身中设置初始值:

constructor(props) {
    super(props);
    this.state = {
       isLoading: true,
       data: {
           labels: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
           datasets: [
               {
                   data: []
               }
           ]
       }
    }
}

GetData = () => {
    const self = this;

    return fetch('http://192.168.100.158:3000/data')
        .then((response) => response.json())
        .then((responseJson) => {

            // clone the data from the state
            const dataClone = {...self.state.data}

            const values = responseJson.map(value => value.IMPORTO);

            dataClone.datasets[0].data = values;
    
            self.setState({
                isLoading: false,
                data: dataClone,
            });
    })
    .catch((error) =>{
      console.error(error);
    });
}

render() {

    // since we're now referencing this.state.data, its value 
    // will be updated directly when we update the state
    
    return (
      <View>
          <LineChart
              data={this.state.data}
              width={Dimensions.get("window").width} // from react-native
              height={220}
              yAxisLabel={"$"}
              chartConfig={chartConfig}
              bezier
              style={{
                  marginVertical: 8,
                  borderRadius: 16
              }}
          />
      </View>
    );
}

推荐阅读