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

Firebase实时数据库无法获取Push生成的随机键及多录入页用户信息统一展示问题

嘿,针对你遇到的这两个Firebase相关问题,我来一步步帮你解决:

问题1:获取Push生成的随机键

Firebase的push()方法返回的引用对象本身就携带了生成的随机key,你直接通过.key属性就能拿到它。修改你的用户注册提交代码如下:

_handleSubmit = (values) => {
  auth()
  .createUserWithEmailAndPassword(values.email, values.password)
  .then(() => {
    const userId = firebase.auth().currentUser.uid;
    if (userId) {
      // 先创建push引用,直接获取生成的随机键
      const userDataRef = firebase.database().ref('kullaniciBilgiler/').child(userId).push();
      const pushKey = userDataRef.key; 
      
      userDataRef.set({
        name: values.name,
        surname: values.surname,
        email: values.email,
        pushKey: pushKey // 可选:把key存入数据,方便后续定位修改
      }).then(() => {
        console.log('数据提交成功,PushKey:', pushKey);
      });
    }
  })
  // 别忘加错误捕获
  .catch(error => {
    console.error('注册/提交失败:', error);
  });
}

问题2:读取Firebase数据并解决「Unable to list data sent with push」报错

你当前的读取代码没有正确处理push生成的嵌套结构——push()会在kullaniciBilgiler/{userId}下生成多个带随机key的子节点,直接snapshot.val()得到的是一个以pushKey为键的嵌套对象,不遍历的话无法正常展示数据,这就是报错的原因。

修改你的数据库读取及页面渲染代码,正确遍历子节点并渲染数据:

import React, { Component } from 'react';
import { View, Text, TextInput, ScrollView, SafeAreaView, Image } from 'react-native';
import firebase from 'firebase';

export default class Profile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userEntries: [] // 存储所有录入的用户信息
    };
  }

  componentDidMount() {
    // 组件挂载后再读取数据,避免时机问题
    const userId = firebase.auth().currentUser?.uid;
    if (!userId) {
      console.log('用户未登录');
      return;
    }
    
    const dbRef = firebase.database().ref(`kullaniciBilgiler/${userId}`);
    dbRef.once('value', (snapshot) => {
      const entries = [];
      // 遍历所有push生成的子节点,这是处理push数据的标准方式
      snapshot.forEach(childSnapshot => {
        const entryData = childSnapshot.val();
        entries.push({
          key: childSnapshot.key, // 保存pushKey用于后续操作
          ...entryData
        });
      });
      this.setState({ userEntries: entries });
      console.log('读取到的用户信息:', entries);
    }, (errorObject) => {
      console.log('读取失败: ' + errorObject.name);
    });
  }

  render() {
    const { userEntries } = this.state;
    return (
      <ScrollView>
        <SafeAreaView style={styles.container} >
          <View style={styles.profilePhoto}>
            <Image 
              style={{ width: 100, height: 100, resizeMode: 'contain', marginTop:40 }} 
              source={ require('../../image/logo.png') } 
            />
          </View>
          <View style={styles.profileDetails}>
            {/* 动态遍历已录入的数据生成输入框 */}
            {userEntries.map(entry => (
              <View key={entry.key} style={{flexDirection:'row', marginBottom: 15}}>
                <View style={styles.textBox}>
                  <Text style={styles.textMid}>İsim</Text>
                </View>
                <View style={styles.inputView}>
                  <TextInput 
                    value={entry.name}
                    onChangeText={(text) => this.updateEntry(entry.key, 'name', text)} 
                    style={styles.input} 
                  />
                </View>
                <View style={styles.textBox}>
                  <Text style={styles.textMid}>Soyisim</Text>
                </View>
                <View style={styles.inputView}>
                  <TextInput 
                    value={entry.surname}
                    onChangeText={(text) => this.updateEntry(entry.key, 'surname', text)} 
                    style={styles.input} 
                  />
                </View>
              </View>
            ))}
          </View>
        </SafeAreaView>
      </ScrollView>
    );
  }

  // 可选:添加数据更新方法,通过pushKey定位修改
  updateEntry = (pushKey, field, value) => {
    const userId = firebase.auth().currentUser.uid;
    firebase.database().ref(`kullaniciBilgiler/${userId}/${pushKey}/${field}`)
      .set(value)
      .then(() => console.log('数据更新成功'))
      .catch(error => console.error('更新失败:', error));
  }
}

// 补充样式定义
const styles = {
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#fff'
  },
  profilePhoto: {
    alignItems: 'center'
  },
  profileDetails: {
    width: '90%',
    marginTop: 20
  },
  textBox: {
    width: 80,
    justifyContent: 'center',
    paddingHorizontal: 8
  },
  textMid: {
    fontSize: 16,
    color: '#333'
  },
  inputView: {
    flex: 1,
    borderBottomWidth: 1,
    borderColor: '#ddd',
    marginHorizontal: 5
  },
  input: {
    fontSize: 16,
    paddingVertical: 8
  }
};

关键说明

  • 把数据读取逻辑移到componentDidMount生命周期中,确保组件挂载完成后再执行读取操作,避免时机错误。
  • 使用snapshot.forEach()遍历push生成的子节点,这是Firebase处理push数据的标准方式,能正确获取每一条录入信息。
  • 将读取到的数据存入组件state,通过map()动态生成对应输入框,替代原来固定次数的手动循环。
  • 新增的updateEntry方法可以帮你通过pushKey精准定位到某条录入数据进行修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:02:28