首页 > 解决方案 > React Native Firebase 链接承诺

问题描述

我正在使用 Firebase 节点上设置一个侦听器,然后在数据库使用两次.on('value')添加值后尝试链接多个承诺。.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');
  });

标签: react-nativereact-native-firebase

解决方案


每当设置侦听器的数据发生更改时,“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
}

更多用例:https ://rnfirebase.io/database/usage


推荐阅读