使用Firebase 9与React Native入门教程

1,043 阅读6分钟

使用React Native的Firebase 9入门教程

最近,Firebase推出了Firebase 9版本的库。这使得我们在使用Firebase时与之前的版本产生了一些差异。Firebase第9版的一个重要变化是采用了一种更加模块化和功能化的方法。

这意味着我们只从库中导入我们需要的Firebase函数。以前的版本采用的是面向对象的方法,我们直接在Firebase对象上调用那些函数和方法。在Firebase 9中,你只导入你的具体应用所需要的函数。因此,允许你在你的应用程序中删除任何未使用的代码。

目标

在本指南中,我们将使用Firebase 9和React native,并在React native应用中实现这些新功能。首先,我们将使用React Native和Firebase 9构建一个todos应用程序。

前提条件

要学习本教程,必须具备以下工具。

  • 在你的电脑上安装Node.js
  • 对React Native的基本了解。
  • 对Firebase生态系统的基本了解。
  • 一个已经在Firebase上设置好的账户。

创建和配置一个Firebase项目

确保你已经在Firebase上登录了。前往Firebase控制台,添加一个新的Firebase项目,将其命名为React Native Todo App

add-a-new-project

一旦项目设置完毕,点击继续。你会被重定向到那个新创建项目的控制台。React Native是跨平台的。它同时支持iOS和Android。根据你正在构建的设备,点击其图标,将Firebase添加到应用程序中。

在产生的部分注册应用程序包名或苹果捆绑ID,为Ios构建。然后点击注册应用程序。

application-registration

然后下载为创建的应用程序提供的google-services.json 配置文件。点击下一步,添加Firebase SDK。我们将使用NPM来安装它。

现在你可以到项目控制台去了。我们将使用Firebase Firestore数据库。创建一个云Firestore数据库,并选择以测试模式启动。

cloud-firestore

从可用位置中选择你的位置,然后点击启用。给它一些时间来完成配置,然后数据库就可以了。

在这一点上,我们的项目已经创建并配置好了。在接下来的步骤中,我们将设置React Native项目。

设置React Native应用

在设置React Native应用时,我们将使用Expo CLI,它提供了开始使用React Native的最简单方法。

如果你的电脑上安装了Expo CLI工具,请安装它。

npm i -g expo-cli

运行以下命令以确保我们安全地安装了Expo CLI。已安装的Expo CLI的版本将被记录在你的控制台中。

expo-CLI --version

要使用Expo CLI创建一个React Native应用程序,导航到你想要的项目文件夹并运行以下命令。

expo-cli init react-native-firebase-app

选择一个空白模板并按回车键。给它一些时间来完成安装。

安装完成后,导航到项目文件夹。

cd react-native-firebase-app

从NPM安装Firebase SDK。

npm i firebase

从Expo中安装矢量图标。

expo-cli install @expo/vector-icons

现在应用程序已经为下一步做好了准备。

在应用程序中配置Firebase

在你的项目文件夹中创建一个src 目录,然后在src 里面创建一个firebase 目录。在firebase 目录内,创建一个config.js 文件。

在这个config.js 文件中。

  • 首先导入Firebase和Firestore。
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
  • 创建一个firebaseConfig ,如下所示。
const firebaseConfig = {
    projectId: 'your_project_id',
    appId: 'your_app_id',
}

根据你之前下载的google-services.json 配置文件中保存的凭证,编辑上面的凭证。

  • 如果应用程序没有被初始化,则初始化它。
if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig)
}
  • 导出firebase
export {firebase}

就这样,Firebase在我们的应用程序中被配置好了。在下一步,我们将实现添加todos。

使用todos

src 文件夹中,创建一个components 文件夹。然后,在components 文件夹中,创建两个文件。

  • Todos.js 添加todos视图并与Firebase SDK进行通信。

  • styles.js 来给todos添加样式。

Todos.js 文件中。

  • 首先导入以下包。
import React,{useState,useEffect} from 'react'
import { Text, View,TextInput,TouchableOpacity,FlatList ,Keyboard} from 'react-native';
import { firebase } from "../firebase/config";
import { FontAwesome } from "@expo/vector-icons";
import styles from './styles';
  • 创建组件函数。
export default function Todos() {

    const [todo, setTodo] = useState(''); // todo
    const [todos, setTodos] = useState([]); // todos
    const todoRef = firebase.firestore().collection('todos'); // todos collection reference

    // fetch the saved todos realtime
    useEffect(() => {

        todoRef
            // order by time of creating
            .orderBy('createdAt', 'desc')
            // fetch todos in realtime
            .onSnapshot(
                querySnapshot => {
                    const newTodos = []
                    // loop through the saved todos
                    querySnapshot.forEach(doc => {
                        const todo = doc.data()
                        todo.id = doc.id
                        newTodos.push(todo)
                    });
                    // set the todos to the state
                    setTodos(newTodos)
                },
                error => {
                    // log any error
                    console.error(error);
                }
            )
    }, []);

    // add a todo
    const addTodo = () => {
        // check if we have a todo.
        if (todo && todo.length > 0) {
            // get the timestamp
            const timestamp = firebase.firestore.FieldValue.serverTimestamp();
            // structure the data  to save
            const data = {
                text: todo,
                createdAt: timestamp
            };
            // add the data to firestore db
            todoRef
                .add(data)
                .then(() => {
                    // release todo state
                    setTodo('');
                    // release keyboard
                    Keyboard.dismiss();
                })
                .catch((error) => {
                    // show an alert in case of error
                    alert(error);
                })
        }
    }

    // delete a todo
    const deleteTodo = (todo) => {
        // delete todo from firestore db
        todoRef
            .doc(todo.id)
            .delete()
            .then(() => {
                // show a successful alert
                alert("Deleted successfully");
            })
            .catch(error => {
                // show an error alert
                alert(error);
            })
    }

    // render a todo
    const renderTodo = ({ item }) => {
        return (
            <View style={styles.todoContainer} >

                <Text style={styles.todoText}>
                    {item.text[0].toUpperCase() + item.text.slice(1)}
                </Text>

                <View style={styles.textIcons}>

                    <FontAwesome name="trash-o" color="red" onPress={() => deleteTodo(item)} style={styles.todoIcon} />

                </View>

            </View>
        )
    }

    // View
    return (
        <View style={styles.container}>
            <View style={styles.formContainer}>
                <TextInput
                    style={styles.input}
                    placeholder='Add new todo'
                    placeholderTextColor="#aaaaaa"
                    onChangeText={(text) => setTodo(text)}
                    value={todo}
                    underlineColorAndroid="transparent"
                    autoCapitalize="none"
                />
                <TouchableOpacity style={styles.button} onPress={addTodo}>
                    <Text style={styles.buttonText}>Add</Text>
                </TouchableOpacity>
            </View>
            {todos.length > 0 && (
                <View style={styles.listContainer}>
                    <FlatList
                        data={todos}
                        renderItem={renderTodo}
                        keyExtractor={(todo) => todo.id}
                        removeClippedSubviews={true}
                    />
                </View>
            )}
        </View>
    )
}

在上面的代码块中,我们是。

  • 为todo和todos初始化状态。
  • firestore ,为我们的todos集合设置一个引用。
  • 通过使用querySnapshot 函数实时获取保存的todos。
  • 处理添加todo的功能。
  • 处理删除todos的功能。
  • 从渲染函数中显示一个单一的todo。
  • 显示一个添加todo的表单并显示获取的todos。

最后在styles.js 文件中添加以下样式。

import { StyleSheet } from 'react-native';

export default StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        marginTop:20
    },
    formContainer: {
        flexDirection: 'row',
        height: 80,
        marginTop: 40,
        marginBottom: 20,
        flex: 1,
        paddingTop: 10,
        paddingBottom: 10,
        paddingLeft: 30,
        paddingRight: 30,
        justifyContent: 'center',
        alignItems: 'center'
    },
    input: {
        height: 48,
        borderRadius: 5,
        overflow: 'hidden',
        backgroundColor: 'white',
        paddingLeft: 16,
        flex: 1,
        marginRight: 5
    },
    button: {
        height: 47,
        borderRadius: 5,
        backgroundColor: '#788eec',
        width: 80,
        alignItems: "center",
        justifyContent: 'center'
    },
    buttonText: {
        color: 'white',
        fontSize: 16
    },
    listContainer: {
        marginTop: 20,
        padding: 20,
    },
    todoContainer: {
        marginTop: 16,
        borderBottomColor: '#cccccc',
        borderBottomWidth: 1,
        paddingBottom: 16,
        flex:1,
        justifyContent:'space-between',
        flexDirection:'row',
        width:"100%"
    },
    todoText: {
        fontSize: 16,
        color: '#333333'
    },
    todoIcons:{
        display:'flex',
        flexDirection:"row"
    },
    todoIcon:{
        marginTop:5,
        fontSize:20,
        marginLeft:14,
    },
})

编辑项目文件夹根目录下的App.js 文件,如下所示。

import React from 'react';
import Todos from "./src/components/Todos";

export default function App() {

  return (
    <Todos />
  );
}

我们正在替换模板代码以返回Todos 组件。

测试

在这一点上,我们的应用程序已经准备好进行测试了。确保你有一个连接的设备,即一个实际的设备或一个模拟器。然后,在当前项目文件夹位置的终端上运行以下命令。

npm run android # for android
npm run ios # for ios

由于我们使用的是Expo,该应用程序将从Expo Go应用程序中构建和启动。

对于你第一次登陆时的主屏幕,你应该有一个类似的屏幕。

homepage

添加一些todos,你的屏幕应该看起来类似于。

home-page-with-todos

一旦你删除了一个待办事项,你应该会收到一个提醒,而待办事项的列表也会更新。

home-page-todos-delete

要查看集合的数据,请到你的项目控制台,点击Firestore database 。你应该能够从那里查看你的集合和数据。

总结

这篇文章涵盖了使用React Native和Firebase版本9构建一个简单的todos应用程序。