【问题标题】:React Native firebase realtime database not workingReact Native firebase实时数据库不起作用
【发布时间】:2021-11-13 00:37:26
【问题描述】:

我正在尝试在我的 React Native 项目中使用 Firebase 实时数据库。根据我在 Android 方面所做的文档(我正在检查 Android)。

yarn add @react-native-firebase/app

然后放入 google-services.json 并进行所有 gradle 相关的更改。

yarn add @react-native-firebase/database

我还创建了一个小型测试数据库来测试功能。

这是我在主页上尝试过的代码。

  componentDidMount() {
        console.log("Component Did Mount")

        database()
        .ref('name/')
        .on('value', snapshot => {
          console.log('User data: ', snapshot);
        });
    }

“用户数据”尚未在控制台中打印。不仅是快照值,还有用户数据文本。只有 'component did mount' 文本打印在控制台中。我也在 AndroidMainifest 中添加了所有相关权限

AndroidManifest

    <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />                                               
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

json 包

 "dependencies": {
    "@react-native-async-storage/async-storage": "^1.15.5",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-native-firebase/app": "^12.7.5",
    "@react-native-firebase/database": "^12.7.5",
    "@react-native-firebase/firestore": "^12.7.5",
    "@react-native-firebase/remote-config": "^12.8.0",
    "@react-navigation/bottom-tabs": "^5.11.11",
    "@react-navigation/native": "^5.9.4",
    "@react-navigation/stack": "^5.14.5",
    "@reduxjs/toolkit": "^1.6.0",
    "@thecodingmachine/redux-toolkit-wrapper": "2.0.1",
    "axios": "^0.21.1",
    "i18next": "^20.3.2",
    "prop-types": "^15.7.2",
    "react": "17.0.1",
    "react-i18next": "^11.11.0",
    "react-native": "0.64.2",
    "react-native-flipper": "^0.94.1",
    "react-native-gesture-handler": "^1.10.3",
    "react-native-linear-gradient": "^2.5.6",
    "react-native-reanimated": "^2.2.0",
    "react-native-safe-area-context": "^3.2.0",
    "react-native-screens": "^3.4.0",
    "react-native-webview": "^11.13.0",
    "react-redux": "^7.2.4",
    "redux": "^4.1.0",
    "redux-flipper": "^1.4.2",
    "redux-persist": "^6.0.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "babel-jest": "^26.6.3",
    "babel-plugin-module-resolver": "^4.0.0",
    "eslint": "^7.22.0",
    "eslint-import-resolver-babel-module": "^5.1.2",
    "eslint-plugin-import": "^2.22.0",
    "eslint-plugin-jest": "^24.3.5",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "^0.64.0",
    "react-test-renderer": "17.0.1"
  },

我正在使用这个样板 https://github.com/thecodingmachine/react-native-boilerplate

【问题讨论】:

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


    【解决方案1】:

    DatabaseReference#on() method 接受两个单独的回调,一个用于请求的事件触发,一个用于处理错误。

    database()
      .ref('name') // no trailing "/"! (even though it does get trimmed off internally)
      .on(
        'value',
        snapshot => {
          console.log('Latest value for "/name": ', snapshot);
        },
        error => {
          console.error('Failed to retrieve "/name": ', snapshot);
        }
      );
    

    重要的是,此方法还返回第一个快照侦听回调,以便您在卸载组件时可以将其与DatabaseReference#off 一起使用。

    const nameListener = database()
      .ref('name')
      .on(/* ... */);
    
    // create a callback to be called in the `componentWillUnmount()` method
    const unsubscribeNameListener = () => nameRef.off('value', nameListener);
    

    综合起来得到:

    class NameFromDatabase extends React.Component {
      private unsubscribers = [];
     
      componentDidMount() {
        const nameRef = database().ref('name');
    
        const nameListener = nameRef
          .on(
            'value',
            snapshot => {
              console.log('Latest value for "/name": ', snapshot);
            },
            error => {
              console.error('Failed to retrieve "/name": ', snapshot);
            }
          );
    
        // create a callback to be called in the `componentWillUnmount()` method
        unsubscribers.push(() => nameRef.off('value', nameListener));
      }
    
      componentWillUnmount() {
        unsubscribers.forEach(unsub => unsub());
      }
    }
    

    虽然上述代码有效,但您确实应该改用 React Hooks API 和新的 Firebase SDK 的 Modular API。对于新项目,不建议使用基于类的 React 形式和基于命名空间的 Firebase 版本。

    import { useState, useEffect } from 'react';
    import { getDatabase, ref, onValue, off } from 'firebase/database';
    
    const NameFromDatabase = () => {
      const [name, setName] = useState();
    
      useEffect(() => {
        const nameRef = ref(getDatabase(), 'name');
    
        // onValue returns its own unsubscribe function
        return onValue(
          nameRef,
          snapshot => {
            console.log('Latest value for "/name": ', snapshot.val());
            setName(snapshot.val());
          },
          error => {
            console.error('Failed to retrieve "/name": ', error);
            setName(null);
          }
        );
      }
    
      if (name === void 0)
        return (<div>Loading...</div>);
    
      if (name === null)
        return (<div class="error">Name not found!</div>);
    
      return (<div>{ name }</div>);
    }
    

    【讨论】:

    • 非常感谢您的回复。我已经尝试过您发布的类组件方法。但它仍然无法正常工作。即使它不会进入错误方法。在功能组件上发现一些错误(我认为导入错误..稍后会检查)你能检查一下吗?我也更新了我的 androidmainfest 和 package json
    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多