【问题标题】:receive specific data from Firebase with if statement in React Native使用 React Native 中的 if 语句从 Firebase 接收特定数据
【发布时间】:2020-05-01 06:05:22
【问题描述】:

我是 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”时,它将所有数据置于状态。

【问题讨论】:

    标签: javascript reactjs react-native firebase-realtime-database react-native-firebase


    【解决方案1】:

    如果snapshot 返回一个对象,那么你可以解构它:

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

    然后你可以有这样的检查:

    if(question_number === this.scanOutput){
    

    【讨论】:

      【解决方案2】:

      您的代码正在读取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});
            }
          })
        })
      

      【讨论】:

      • 非常感谢您的解释!不幸的是,当我尝试代码时,出现以下错误:TypeError: undefined is not a function (near) '... questions.map ...') 也许你对此有解释?
      • 感谢代码有效!我试图读取一个对象而不是一个数组。你的这段代码是完全正确的!非常感谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 2017-11-04
      • 1970-01-01
      • 2021-10-13
      • 2021-08-25
      相关资源
      最近更新 更多