【问题标题】:What's wrong with my Fire Base code (React Native)我的 Fire Base 代码有什么问题(React Native)
【发布时间】:2018-04-05 09:59:12
【问题描述】:

尝试使用 Firebase 在 React Native 中设置一些测试数据。我已使用$yarn add firebase 成功安装。我在 FB 中添加了这样的测试数据: FB data 在我的项目中,我添加了以下代码:

import * as firebase from 'firebase' 

const firebaseConfig = {
    apiKey: "AIzaSyBNKM6Ptbynkg5dEJkwMHNsZhUCsW2JqGE",
    authDomain: "testproject-f4c9f.firebaseapp.com",
    databaseURL: "https://testproject-f4c9f.firebaseio.com",
    projectId: "testproject-f4c9f",
    storageBucket: "testproject-f4c9f.appspot.com",
    messagingSenderId: "48530616964"
}
firebase.initializeApp(firebaseConfig)

然后在渲染中:

let mytext = ""

let testing = 
firebase.database().ref('testCategory/test1/FirstHeader');

testing.on('value', function(snapshot) {
    mytext = snapshot.val()
});

return(
    <View>
       <Text>{mytext}</Text>
    </View>
);

运行应用程序,没有任何显示。任何想法将不胜感激。

更新: 我设法用这个代码在console.log 中得到它:

let child = ""

var ref = firebase.database().ref("testCategory");

ref.once("value")
.then(function(snapshot) {
child = snapshot.child("test1/testHeader").val() 
console.log({child})
});

但由于某种原因,我无法在文本输出中打印出来:

return(
    <View>
       <Text>{this.child}</Text>
    </View>
);

它只是空白......

【问题讨论】:

  • 尝试放快照日志,检查是否有数据?
  • 不,它是空的:/
  • 现在可以在控制台上使用,但不能在文本视图中使用:请参阅更新。

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


【解决方案1】:

您需要将数据从回调传递到视图。你应该使用像 Redux 或 MobX 这样的状态管理器,但是对于这个例子,你可以只使用组件状态。

这就是您的组件的外观。

class Hello extends Component {
  state = {
    child: ''
  }

  componentDidMount() {
    firebase
      .database()
      .ref('testCategory')
      .on('value')
      .then(snapshot => {
        const child = snapshot.child('test1/testHeader').val()

        this.setState({
          child
        })
      })
  }

  render() {
    const { child } = this.state

    return (
      <View>
        <Text>{child}</Text>
      </View>
    )
  }
}

多田!

【讨论】:

  • 谢谢,但我收到一条错误消息 "Cannot read property 'child' of null",因为日志输出显示了一个字符串,所以这毫无意义。
  • 你需要在你的组件中设置state。我会用完整的代码更新我的答案。
  • 非常感谢您的帮助,非常感谢!除了一个细节之外,它起作用了:我必须绑定它,否则我在 this.setState 上遇到错误。将this.setState( { child }) }.bind(this)); //BINDING TO SET STATE } 添加到您的编辑中,我很乐意接受已解决问题的答案。 :)
  • 这就是为什么我将setState 放在一个闭包中,所以this 保留了正确的范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
相关资源
最近更新 更多