react-native - React Native:从 Firebase 获取数据
问题描述
我只是想从 Firebase 的数据库中检索数据,这就是我所拥有的
var userList = [];
firebase.database()
.ref('/users/')
.once('value')
.then(snapshot => {
snapshot.forEach((doc) => {
userList.push(doc.val());
});
});
console.log(userList);
即使我从教程中复制并粘贴了此代码,用户列表在快照之外也是空的。你能告诉我这是为什么吗?
解决方案
对 firebase 的请求是异步的,因此console.log(userList);
在被调用之前userList.push(doc.val());
被调用。
您应该创建userList
一个组件状态变量,以便在更新它时您的组件将重新呈现。
像下面这样的东西应该可以工作:
class UserListComponent extends Component {
constructor(props) {
super(props);
this.state = {
userList: [],
};
}
componentDidMount() {
this.getUsers();
}
getUsers() {
firebase
.database()
.ref('/users/')
.once('value')
.then((snapshot) => {
snapshot.forEach((doc) => {
this.setState({
userList: [...this.state.userList, doc.val()],
});
});
});
}
render() {
return (
<View>
{this.state.userList.map((item) => {
return (
<View>
<Text>{item.name}</Text>
</View>
);
})}
</View>
);
}
}
推荐阅读
- php - 实体属性的 API 平台自定义 getter 名称
- php - 使文本框和按钮占据整个 div
- java - 错误:无法执行 android:onClick 的方法
- php - get() 函数在 laravel 8 更新版本上不起作用
- node.js - 强制 /login/callback 护照 nodejs
- html - HTML/CSS:重复-y,背景模糊
- angular -
在 Angular 8 应用程序中不能以反应形式工作 - c# - VSCode .Net Core MVC 报告问题,但项目构建和运行正常
- javascript - Wordpress 中的传单地图 - 弹出窗口不起作用
- python - Plotly Dropdown 输出图表