React Native Firebase 链接承诺
React Native Firebase chaining promises
我正在使用 .on('value')
在 Firebase 节点上设置一个侦听器,然后在数据库使用 .then()
两次增加值后尝试链接多个承诺。
但是我收到错误 firebase.database().ref().on(...., *) 'callback' must be a function
知道如何解决这个问题吗?
database()
.ref('profiles/users/' + user.uid)
.on('value')
.then(snapshot => {
console.log(snapshot);
})
.then(() => {
console.log('Whatever');
});
只要监听器设置的数据发生变化,'on'监听器就会使用回调函数,这就是您的错误所在,因为您没有提供回调。您可以轻松地在该回调中完成任何数据操作,而无需链接一堆“.then”。下面是数据变化后设置状态的例子。
import React, { useEffect, useState } from 'react';
import database from '@react-native-firebase/database';
function User({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
const subscriber = database();
subscriber.ref(`/users/${userId}`).on('value', snapshot => {
setUser(snapshot.val());
//or call another function that will do the rest of the async tasks/data manipulation
});
// Stop listening for updates when no longer required
return () => subscriber();
}, [userId]);
// return whatever here
}
我正在使用 .on('value')
在 Firebase 节点上设置一个侦听器,然后在数据库使用 .then()
两次增加值后尝试链接多个承诺。
但是我收到错误 firebase.database().ref().on(...., *) 'callback' must be a function
知道如何解决这个问题吗?
database()
.ref('profiles/users/' + user.uid)
.on('value')
.then(snapshot => {
console.log(snapshot);
})
.then(() => {
console.log('Whatever');
});
只要监听器设置的数据发生变化,'on'监听器就会使用回调函数,这就是您的错误所在,因为您没有提供回调。您可以轻松地在该回调中完成任何数据操作,而无需链接一堆“.then”。下面是数据变化后设置状态的例子。
import React, { useEffect, useState } from 'react';
import database from '@react-native-firebase/database';
function User({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
const subscriber = database();
subscriber.ref(`/users/${userId}`).on('value', snapshot => {
setUser(snapshot.val());
//or call another function that will do the rest of the async tasks/data manipulation
});
// Stop listening for updates when no longer required
return () => subscriber();
}, [userId]);
// return whatever here
}