firebase - 无法从 firebase 数据库映射数据数组
问题描述
我正在制作一个血库应用程序,但我遇到了一个问题,我无法在 react native JSX 中映射我的数据列表。我从我之前在 react native 中制作的todoApp中复制了大部分代码并对其进行了修改。我还希望它在用户打开应用程序时自动获取所有数据,而不是手动使用按钮。
APP.JS:
import React from 'react';
import {Button,Text, View, ScrollView} from 'react-native';
import firebase from 'firebase';
const firebaseConfig = {
apiKey: "AIzaSyBPAEj0ku0YBF1DzCc1b6mGpEKz0Bhn9Fk",
authDomain: "bloodbank-pro.firebaseapp.com",
projectId: "bloodbank-pro",
storageBucket: "bloodbank-pro.appspot.com",
messagingSenderId: "533183192799",
appId: "1:533183192799:web:82b1a608af84d64e6d536a",
measurementId: "G-06F49XSLF4"
};
firebase.initializeApp(firebaseConfig);
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {
list: [],
}
}
work=()=>{
firebase.database().ref().once('value').then(snapshot => {
var snap = snapshot.val();
var newStateArray = this.state.list.slice();
newStateArray.push({id: this.state.list.length + 1,username: snap.username, age: snap.age, bloodtype: snap.bloodtype, phonenumber: snap.phonenumber});
this.setState({list: newStateArray,});
});
}
render(){
return(<>
<ScrollView style={{ backgroundColor: 'white', marginVertical:20 }} showsVerticalScrollIndicator={true}>
<View>
{this.state.list.map(item => (<>
<View key={item.id} style={{borderBottomColor: 'black',borderBottomWidth: 5, marginBottom: 20}}>
<Text style={{fontSize: 22}}>{item.username}, {item.age}, {item.phonenumber}, {item.bloodtype}</Text>
</View>
</>))}
</View>
</ScrollView>
<View style={{position: 'absolute', bottom: 1, left: 1, right: 1,}}>
<Button title="test" onPress={this.work} />
<Button title="Go to My Profile" />
</View>
</>)
}
}
这是在 react native CLI 中制作的。我将非常感谢您的帮助。
解决方案
可能,您的应用程序正试图在数据库完全初始化之前获取数据。最好的做法是将
const firebaseConfig = {
apiKey: "AIzaSyBPAEj0ku0YBF1DzCc1b6mGpEKz0Bhn9Fk",
authDomain: "bloodbank-pro.firebaseapp.com",
projectId: "bloodbank-pro",
storageBucket: "bloodbank-pro.appspot.com",
messagingSenderId: "533183192799",
appId: "1:533183192799:web:82b1a608af84d64e6d536a",
measurementId: "G-06F49XSLF4"
};
firebase.initializeApp(firebaseConfig);
在index.js
您的项目中。在你的index.js
文件中写
componentDidMount() {
const firebaseConfig = {
apiKey: "AIzaSyBPAEj0ku0YBF1DzCc1b6mGpEKz0Bhn9Fk",
authDomain: "bloodbank-pro.firebaseapp.com",
projectId: "bloodbank-pro",
storageBucket: "bloodbank-pro.appspot.com",
messagingSenderId: "533183192799",
appId: "1:533183192799:web:82b1a608af84d64e6d536a",
measurementId: "G-06F49XSLF4"
};
firebase.initializeApp(firebaseConfig);
}
在App.js
文件中写入:
componentDidMount(){
this.work()
}
推荐阅读
- python - 为 SQL 机器学习安装 microsoftml 和 revoscalepy
- javascript - 为什么我的 Javascript 代码中的随机数是连接而不是添加?
- python - 在 for 循环中酸洗列表
- docker - 如何在 filebeat.yml 文件中使用变量
- visual-studio - Visual Studio 中缺少 macOS 模板
- c# - 我有一张收据表格,我需要将此表格 tex 框链接到其他表格中的其他文本框,我该怎么做?
- sql - 如何在动态 SQL 中包含中断?
- java - 如何在 Secure_CRT 上远程编辑 zip 内的文件?
- java - 使用超类的变量访问派生类的对象
- angular - 从服务器获取数据后,角度材料表排序不起作用