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

React Native从Firebase拉取数据重复显示如何解决?

问题根因
  • 你查询的LevelData/{用户uid}节点下直接包含data和Top3Data两个子字段,无需遍历子节点
  • 原有代码使用snapshot.forEach遍历该节点下的所有子项,该节点刚好存在2个子节点,所以会循环2次,每次都把整份data和Top3Data塞入数组,最终state的list数组长度为2,map渲染时就出现2份重复图表
修复方案

1. 修改state定义

constructor(props) {
  super(props);
  this.state = {
    topData: {}, // 存储Top3Data对应数据,用于顶部图表
    bottomData: {} // 存储data对应数据,用于底部图表
  };
}

2. 重构数据拉取逻辑,移除多余的forEach遍历

componentDidMount(){
  const user = firebase.auth().currentUser.uid;
  const db = firebase.database();
  const ref = db.ref('LevelData/'+`${user}`);
  ref.on('value',(snapshot)=>{
    const nodeValue = snapshot.val();
    this.setState({
      topData: nodeValue.Top3Data,
      bottomData: nodeValue.data
    })
  })
}

3. 修改渲染方法,无需map遍历直接渲染单份图表

renderLevel(){
  return (
    <View style={styles.botChartsView} >
      <ProgressChart
        data={this.state.bottomData}
        width={120}
        height={180}
        strokeWidth={16}
        radius={32}
        hideLegend={false}
        strokeWidth={20}
        chartConfig={{
          backgroundColor: "#e26a00",
          backgroundGradientFrom: "#fb8c00",
          backgroundGradientTo: "#ffa726",
          decimalPlaces: 2,
          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"
          }
        }}
      />
    </View>
  )
}

renderLevel1(){
  return (
    <ProgressChart
      data={this.state.topData}
      width={320}
      height={200}
      strokeWidth={16}
      radius={32}
      hideLegend={false}
      strokeWidth={20}
      chartConfig={{
        backgroundColor: "#e26a00",
        backgroundGradientFrom: "#fb8c00",
        backgroundGradientTo: "#ffa726",
        decimalPlaces: 2,
        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"
        }
      }}
    />
  )
}
参考截图
  • 数据库截图:数据库截图
  • 控制台输出截图:控制台输出截图
  • 应用页面截图:应用页面截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:45:02