React Native Firebase ref.once永远不会被解雇

时间:2017-05-29 06:00:55

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

我正在使用firebase数据库运行react本机项目。

这是我先试过的:

firebase.database.ref("foo").once("value", function(s){console.log(s);});

直觉上,我认为这会在某个时候被调用,如果foo不存在,它将返回一个空快照。但这永远不会开火。

然后我尝试了:

var fooRef = firebase.database.ref("foo");
fooRef.once("value", function(s){console.log(s);});

这也不会解雇。也没有:

var fooRef = firebase.database.ref("foo");
fooRef.once("value").then(function(s){console.log(s);});

然而,

var fooRef = firebase.database.ref("foo");
fooRef.set("bar");
fooRef.once("value", function(s){console.log(s);});

开枪了。在此之后没有其他任何其他键的读取 - 它只读取前一条指令中写入的内容。

我花了大约5个小时尝试了所有firebase的故障排除提示,而且我现在感到非常沮丧,因为它似乎无法以其声称的任何方式工作。读取/写入用户ref在index.android.js中工作正常,但fooRef仅适用于index.android.js。

编辑:在下方添加完整代码:

async getItems(obj, end_id) {
        uid = await AsyncStorage.getItem("@user:uid");
        console.log("User id: " + uid)
        console.log("App: " + firebase.database().app.name);
        var listening = true;
        firebase.database().ref("/user/" + uid + "/seen").once("value", function (snapshot) {
            console.log("Got snapshot for seen reference.")
            data = snapshot.val();
            discount = data.split(",");
            console.log(discount)
            cards = []
            console.log("Waiting to populate cards...");
            listening = false;
        });
        console.log("Attempted to receive reference of seen.");
        while(listening); listening=true;
        firebase.database().ref("/users/"+uid).once("value", function(snapshot) {
            console.log("Got snapshot of users.");
            data = snapshot.val();
            if (discount.indexOf(data.id) < 0) {
                cards.unshift({
                    heading: data.title, subtitle: data.category,
                    image: data.uri, likes: data.likes,
                    id: data.id
                });
            }
            listening = false;
            waiting = false;
        });
        while (cards.length == 0); waiting = false; obj.setState({});
}
....
constructor(props) {
    super(props)
    getItems(this,99999)
}
//waiting is a global variable

1 个答案:

答案 0 :(得分:0)

Firebase.database是函数,你需要将/添加到ref,因为ref是数据库的路径,所以你应该这样写

firebase.database().ref('/foo').once('value').then(function(s){console.log(s.val());})