首页 > 解决方案 > React Native:从 Firebase 获取数据

问题描述

我只是想从 F​​irebase 的数据库中检索数据,这就是我所拥有的

var userList = [];
    
    firebase.database()
  .ref('/users/')
  .once('value')
  .then(snapshot => {
    snapshot.forEach((doc) => {
      
      userList.push(doc.val());
      
    });
    
  });
  
  console.log(userList);

即使我从教程中复制并粘贴了此代码,用户列表在快照之外也是空的。你能告诉我这是为什么吗?

标签: react-native

解决方案


对 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>
    );
  }
}


推荐阅读