在 React Native 中使用 if 语句从 Firebase 接收特定数据

receive specific data from Firebase with if statement in React Native

我是 Firebase 和 React Native 的新手。我已经创建了一个数据库,现在当某个数字等于 firebase 中 1 个对象中的数字时,它将此数据存储在一个数组中。 我有以下代码:

scanOutput = '0';

getUserData = () => {
    console.log(this.scanOutput);
    let ref = firebase.database().ref('Questions/1R1/NL');
    ref.on('value' , snapshot =>{
      var state = snapshot.val();

      console.log(state);

      if('1' === this.scanOutput){
        this.setState({questions: state});
      }
    })

  }

  componentDidMount(){
    this.scanOutput = this.props.navigation.getParam('output'); 
    this.getUserData();
  }

数据库如下所示:

目前 if 语句包含一个硬编码的“1”,我想要实现的是当 this.scanOutput(在本例中为“1”)等于数据库中的 "question_number" 时,它将所有状态中的数据。

如果snapshot returns你是一个对象那么你可以解构它:

const { question_number } = snapshot.val();
console.log(question_number);

然后你可以像这样检查:

if(question_number === this.scanOutput){

您的代码正在读取 Questions/1R1/NL 下的所有数据。由于下面可能有多个问题,所以 snapshot 可能包含多个子节点。您的回调需要通过遍历 snapshot.forEach.

来处理这些问题

像这样:

  let ref = firebase.database().ref('Questions/1R1/NL');
  ref.on('value' , snapshot =>{
    snapshot.forEach((question) => {
      var state = question.val();

      if(state.question_number === this.scanOutput){
        this.setState({questions: state});
      }
    })
  })