0

我是 React Native 的新手,我正在尝试在 Firebase 实时数据库中绘制实时数据图。

这是我的数据库结构:

在此处输入图像描述

我正在尝试使用“react-native-svg-charts”绘制折线图,​​其中 X 轴具有日期值,Y 轴具有“睡眠”值 - 添加新节点时也会更新。

我可以从 firebase 获取所需的数据并将其附加到相应的数组中。

睡眠者: 睡眠者 约会者: 日期

当我使用静态数组并对值进行硬编码时 - 我能够正确绘制图形。 绘制的硬编码值

但是当我使用包含来自 Firebase 的快照数据和 on() 方法的 datearr 和 sleeparr 时 - 我只得到一个空白图(即使在 console.log() 中两个数组都是正确的)。 空白图表

我的代码:

    render() {
        const sleeparr = []
        const sleep = db.ref('symptoms/');
        sleep.on('value', function(snapshot) {
          snapshot.forEach((childSnapshot) => {
          sleeparr.push(childSnapshot.val().sleep);
          });
          console.log(sleeparr);
        });


        const datearr =[]
        const date = db.ref('symptoms/');
          date.on('value', function(snapshot) {
          snapshot.forEach((childSnapshot) => {
            datearr.push(childSnapshot.val().date);   
          });
          console.log(datearr); 
});

        const axesSvg = { fontSize: 5, fill: '#008384', fontWeight: "400" };
        const verticalContentInset = { top: 10, bottom: 10 }
        const xAxisHeight = 30

        return (
            <View style={styles.container}>
                            <Text style={styles.heading}>Sleep Graph</Text>
            <View style={{ height: "80%", padding: 40, flexDirection: 'row' }}>

                <YAxis
                    data = {sleeparr}
                    style={{ marginBottom: xAxisHeight }}
                    contentInset={verticalContentInset}
                    svg={axesSvg} 

                />
                <View style={{ flex: 1, marginLeft: 10 }}>
                    <LineChart
                        style={{ flex: 1 }}
                        data={sleeparr}
                        contentInset={verticalContentInset}
                        svg={{ stroke: '#00bcd4', strokeWidth: 1.5 }}
                    >
                        <Grid/>
                    </LineChart>
                    <XAxis
                        style={{ marginHorizontal: -10, height: xAxisHeight }}

                       data = { datearr}
                       // formatLabel={(value, index) => value}
                       // formatLabel={(value, index) => datearr.value}                    
                        contentInset={{ left: 10, right: 10 }}
                        svg={axesSvg}
                    />
                </View>
            </View>
            </View>
        )
    }

}

export default SleepPlot

谁能告诉我我做错了什么以及如何正确显示图表?(日期值是字符串也是一个问题吗?)

请帮忙。

@aman - 合并了此更改 - 但图表不显示:

class StressPlot extends React.PureComponent {
    constructor(props)
    {
      super(props);
      this.state = ({
        stressarr : [],
        datearr : [],
      });
    }

    fetch_data = () => {
      const stress = db.ref('symptoms/');
      stress.on('value', (snapshot) => {
        let array1 = []
        snapshot.forEach((childSnapshot) => {
          array1.push(childSnapshot.val().stress);
        });
        for (let x = 0; x <= array1.length; x++) {
          this.state.stressarr.push({
            x: x,y: JSON.parse("[" + array1 + "]")[x]
          });
        }
      });

      stress.on('value', (snapshot) => {
        let array2 = []
        snapshot.forEach((childSnapshot) => {
          array2.push(childSnapshot.val().date);
        });
        for (let x = 0; x <= array2.length; x++) {
          this.state.datearr.push({
            x: x,y: JSON.parse("[" + array2 + "]")[x]
          });
        }
      });
    }

    render() {
          const axesSvg = { fontSize: 15, marginLeft: 50, padding: 50, fill: '#008384', height: "30%",fontWeight: "400" };
          const xaxesSvg = { fontSize: 10, alignSelf: "stretch", flex:2, flexDirection: "space-around" , padding:40, marginBottom:40, fill: '#008384', fontWeight: "400" };
          const verticalContentInset = { top: 30, bottom:40, right: 40, lrft : 40 }
          const xAxisHeight = 30

                return (
                    <View style={styles.container}>

                                    <Text style={styles.heading}>Trend of Daily Parameter - Stress Levels
                                    </Text>
                                    <Text style={styles.semiHeading}>March-April 2020</Text>
                    <ScrollView horizontal={true} style={{ height: "70%", width: "100%", flexDirection: 'row' }}>

                        <YAxis
                            // Y AXIS DATA ARRAY
                            data = { this.state.stressarr }
                            style={{ marginBottom: xAxisHeight }}
                            contentInset={verticalContentInset}
                            svg={axesSvg} 

                         />
                         <View style={{ flex: 1, marginLeft: 10, marginRight: 20, width: 1800, height: "100%", marginBottom: 40 }}> 

                            <LineChart
                                style={{ flex: 1 , marginLeft: 5, marginRight: 1, justifyContent: 'space-around'}}
                                data={this.state.stressarr}
                                contentInset={verticalContentInset}
                                svg={{ stroke: '#00bcd4', strokeWidth: 1.5,}}
                            >
                                <Grid/>
                            </LineChart>
                            <XAxis
                                style={{ marginHorizontal: -10, height: xAxisHeight }}
                                // X AXIS DATA ARRAY
                                data = { this.state.datearr }
                                formatLabel={ (value, index) => dates[index].date }                    
                                contentInset={{ left: 10, right: 10 }}
                                svg={xaxesSvg}
                            /></View>
                        </ScrollView></View>
                )
            }        
        }
        export default StressPlot
        const styles = StyleSheet.create({
            container: {
                display: 'flex',
                flex: 1,
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: '#d6ffff',
                height: Dimensions.get('window').height,
                width: Dimensions.get('window').width,
          },
            heading: {
              color:'#00bcd4',
              fontWeight: "400",
              fontSize: 20,
              marginBottom: 5,
              marginVertical: 30,
            },
            semiHeading: {
              color:'#008384',
              fontWeight:"400",
              fontSize:15,
              justifyContent: 'flex-end',
              marginBottom: 25,
            }
          });
4

1 回答 1

0

使用状态

constructor() {
     super();
     this.state = {
         sleeparr: [],
     };
}

然后获取数据并推送到 sleeparr 数组

 fetch_data = () => {
     const sleep = db.ref('symptoms/');
     sleep.on('value', (snapshot) => {
         let array = []
         snapshot.forEach((childSnapshot) => {
              array.push(childSnapshot.val().sleep);
         });
         for (let x = 0; x <= array.length; x++) {
             this.state.sleeparr.push({
                 x: x, y: JSON.parse("[" + array + "]")[x]
             });
         }
    });
}

最后使用 skelton 作为占位符

{this.state.sleeparr.length === 0 ? (
    <Skeleton
         variant="rect"
         width={650}
         height={420}
         style={{ marginTop: 20 }}
    />
    ) : (
    <LineChart
          data={this.state.sleeparr}
          viewBoxWidth={550}
          pointsStrokeColor="#000"
          areaColor="#000"
          areaVisible={false}
          gridVisible={false}
          pathColor="#f00"
          pathWidth={2}
          abelsColor="#000"
    />)
}

(我使用 Material-ui 中的 Skelton)(从“@material-ui/lab/Skeleton”导入 Skeleton;)

于 2020-04-13T11:24:49.673 回答