您的位置:首页 > Web前端 > React

如何构建React Native应用并将其与Firebase集成

2020-08-21 05:23 1321 查看

In this tutorial, we are going to build a React Native app that is integrated with a Firebase backend. The app will support both the React Native CLI as well as Expo CLI.

在本教程中,我们将构建一个与Firebase后端集成的React Native应用。 该应用程序将支持React Native CLI和Expo CLI。

This React Native Firebase tutorial will cover the main features such as authentication, registration, and database (Firestore) CRUD operations.

这个React Native Firebase教程将涵盖主要功能,例如身份验证,注册和数据库(Firestore)CRUD操作。

You can also download the full source code from Github if you want to jump straight into the code.

如果您想直接跳入代码 ,也可以从Github 下载完整的源代码。

This tutorial will walk you through the details of the following sections:

本教程将引导您完成以下各节的详细信息:

  1. Creating a Firebase project

    创建Firebase项目

  2. Creating & configuring a new React Native app

    创建和配置新的React Native应用

  3. Setting up the folder structure, routes, and navigation

    设置文件夹结构,路线和导航

  4. Implementing the UI for Login, Registration, and Home screens

    实施用于登录,注册和主屏幕的UI

  5. Registration with Firebase Auth

    使用Firebase Auth注册

  6. Login with Firebase Auth

    使用Firebase身份验证登录

  7. Persistent Login Credentials

    永久登录凭证

  8. Writing and reading data from Firebase Firestore

    从Firebase Firestore写入和读取数据

Without further ado, let’s start building out the React Native Firebase project. The final mobile app will look like this:

事不宜迟,让我们开始构建React Native Firebase项目。 最终的移动应用程序将如下所示:

1.创建一个Firebase项目 (1. Create a Firebase Project)

Head over to Firebase.com and create a new account. Once logged in, you’ll be able to create a new project in the Firebase Console.

转到Firebase.com并创建一个新帐户。 登录后,您将能够在Firebase Console中创建一个新项目。

  • Create a new account on Firebase.com

    Firebase.com上创建一个新帐户

  • Create a new project in Firebase Console

    Firebase控制台中创建一个新项目

  • Enable Email & Password auth method in Firebase Console -> Authentication -> Sign-in method

    在Firebase控制台中启用“电子邮件和密码”身份验证方法-> 身份验证 -> 登录方法

  • Create a new iOS app, with App ID com.reactnativefirebase

    使用App ID com.reactnativefirebase创建一个新的iOS应用

  • (Optional) Create a new Android app with package name com.reactnativefirebase

    (可选)使用包名称com.reactnativefirebase创建一个新的Android应用

  • Download the configuration file generated at the next step to your computer (GoogleService-Info.plist for iOS, and google-services.json for Android)

    将下一步生成的配置文件下载到您的计算机上(iOS版为GoogleService-Info.plist ,Android版为google-services.json )

Firebase allows you to build backendless apps. It’s a product running on top of Google Cloud, and allows developers to build web and mobile apps without needing their own servers.

Firebase允许您构建无后端应用程序。 它是在Google Cloud之上运行的产品,可让开发人员无需自己的服务器即可构建Web和移动应用程序。

This saves a lot of time, since you don’t need to write any backend code. It’s also highly scalable, being backed by Google infrastructure.

由于您无需编写任何后端代码,因此可以节省大量时间。 它也具有高度的可扩展性,并得到Google基础架构的支持。

In Firebase, you’ll be able to store everything that’s needed for your app — users, data, files, push notification tokens, etc. All this information is made available to the mobile clients via the Firebase SDKs, which are compatible with React Native. This means that all the interactions with the backend is abstracted out and encapsulated in the SDK, so mobile developers don’t need to worry about API calls, data parsing, sockets management, and so on.

在Firebase中,您将能够存储应用程序所需的所有内容-用户,数据,文件,推送通知令牌等。所有这些信息都可以通过与React Native兼容的Firebase SDK提供给移动客户端。 。 这意味着与后端的所有交互都被抽象出来并封装在SDK中,因此移动开发人员无需担心API调用,数据解析,套接字管理等等。

2.创建和配置一个新的React Native App (2. Create and Configure a New React Native App)

We’re going to make our React Native Firebase app compatible with both Expo CLI and React Native CLI.

我们将使我们的React Native Firebase应用程序与Expo CLI和React Native CLI兼容。

We’re going to use Expo for now, since it makes it easy for newcomers to preview their apps. But we won’t use any Expo specific libraries, so the src code can be simply used in any React Native app, regardless of its scaffolding.

我们现在将使用Expo,因为它使新手可以轻松预览他们的应用程序。 但是我们不会使用任何Expo特定的库,因此src代码可以简单地在任何React Native应用中使用,无论其脚手架如何。

We are going to use the Firebase Web SDK, which is compatible with both Expo and React Native CLI, and is supported directly by Google.

我们将使用Firebase Web SDK ,它与Expo和React Native CLI都兼容,并且由Google直接支持。

If you want to use react-native-firebase instead, feel free to install and configure that (the code will still be the same). But keep in mind that we don’t recommend it for a few reasons:

如果您想改用react-native-firebase ,请随意安装和配置(代码仍然相同)。 但是请记住,出于以下几个原因,我们不建议您这样做:

  • it is not directly supported by Google, so maintaining it will be much harder given it’s an extra layer that can cause bugs, and

    它不受Google的直接支持,因此要进行维护会很困难,因为它是一个额外的层,可能会导致错误,并且
  • it also doesn’t work with Expo, which can be a deal breaker for many developers.

    它也不适用于Expo,对于许多开发人员而言,Expo可能会破坏交易。

The steps below are also covered in the official React Native documentation on how to set up your dev environment.

在React Native官方文档中还介绍了以下步骤,有关如何设置开发环境

  • Install Expo CLI

    安装Expo CLI

In your Terminal, simply run

在您的终端中,只需运行

npm install -g expo-cli
  • Create a new React Native app by running

    通过运行来创建一个新的React Native应用
expo init react-native-firebase

For the template, choose the Managed Workflow — Blank

对于模板,选择“ 托管工作流” - 空白

  • Start the app by running

    通过运行启动应用
yarn ios
// or
yarn android

This will also present you with a QR code which you can scan using the Camera app on iOS, or the Expo app on Android.

这还将为您提供一个QR码,您可以使用iOS上的“相机”应用程序或Android上的Expo应用程序进行扫描。

This is great. We now have a new React Native app, running on both iOS and Android. Let’s start connecting it to your Firebase backend.

这很棒。 现在,我们有了一个新的React Native应用程序,可在iOS和Android上运行。 让我们开始将其连接到Firebase后端。

  • Add the Firebase SDK to the React Native project

    将Firebase SDK添加到React Native项目
yarn add firebase
  • Add React Native Navigation library by running

    通过运行添加React Native Navigation库
yarn add @react-navigation/native && yarn add @react-navigation/stack && expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view
  • Add various UI components and packages to be used in the project

    添加要在项目中使用的各种UI组件和程序包
yarn add react-native-keyboard-aware-scroll-view base-64

Create a Firebase config file

创建Firebase配置文件

mkdir src src/firebase && touch src/firebase/config.js

Add your firebase configuration into src/firebase/config.js:

将您的Firebase配置添加到src / firebase / config.js中:

You can get all this information from Firebase Console -> Project Settings

您可以从Firebase控制台 ->项目设置中获取所有这些信息。

3.创建文件夹结构并设置路线和导航 (3. Create the Folder Structure and Set Up Routes and Navigation)

  • Create the folder structure by running

    通过运行创建文件夹结构
mkdir src/screens src/screens/LoginScreen src/screens/RegistrationScreen src/screens/HomeScreen
  • Create the files structure by running

    通过运行创建文件结构
touch src/screens/index.js src/screens/LoginScreen/LoginScreen.js src/screens/LoginScreen/styles.js src/screens/RegistrationScreen/RegistrationScreen.js src/screens/styles.js src/screens/HomeScreen/HomeScreen.js src/screens/HomeScreen/styles.js
  • Add this code to src/screens/index.js

    将此代码添加到src / screens / index.js

export { default as LoginScreen } from './LoginScreen/LoginScreen'

export { default as HomeScreen } from './HomeScreen/HomeScreen'

export { default as RegistrationScreen } from './RegistrationScreen/RegistrationScreen'

Don’t worry if the project is broken! Everything will make sense in a little while.

不用担心项目坏了! 一会儿,一切都会变得有意义。

  • Set up the routes & navigators

    设置路线和导航器

Override App.js file with the following code snippet:

使用以下代码段覆盖App.js文件:

4.实施用户界面 (4. Implement the UI)

Now that we have the scaffold of the app, let’s go ahead and implement the UI components of all screens. We’re not going into the details of flex layout and React Native styling, since that is outside the scope for this tutorial. We’re going to focus mostly on React Native Firebase integration.

现在我们有了应用程序的支架,让我们继续并实现所有屏幕的UI组件。 我们不会讨论Flex布局和React Native样式的细节,因为这不在本教程的讨论范围之内。 我们将主要集中在React Native Firebase集成上。

Simply override the files as follows:

只需按如下所示覆盖文件:

  • src/LoginScreen/LoginScreen.js

    src / LoginScreen / LoginScreen.js
  • src/LoginScreen/styles.js

    src / LoginScreen / styles.js
  • src/RegistrationScreen/RegistrationScreen.js

    src / RegistrationScreen / RegistrationScreen.js
  • src/RegistrationScreen/styles.js

    src / RegistrationScreen / styles.js
  • src/HomeScreen/HomeScreen.js

    src / HomeScreen / HomeScreen.js
  • src/HomeScreen/styles.js

    src / HomeScreen / styles.js

At this point, your app should run properly and display the following screens (UI only):

此时,您的应用应该可以正常运行并显示以下屏幕(仅限UI):

You can switch between the two screens by tapping the links buttons in the footer.

您可以通过点击页脚中的链接按钮在两个屏幕之间切换。

Now that we have a beautiful UI for login and sign up, let’s see how we can integrate our React Native (and Expo) app with Firebase.

现在我们有了一个漂亮的UI来登录和注册,让我们看看如何将React Native(和Expo)应用程序与Firebase集成在一起。

5. React Native Firebase-注册 (5. React Native Firebase — Registration)

Let’s start with creating a new account with Firebase Auth, since naturally login comes after. For this, we are going to add the Firebase logic for creating a new account with email & password in RegistrationScreen.js, by implementing the onRegisterPress method as follows:

让我们开始使用Firebase Auth创建一个新帐户,因为自然会随后登录。 为此,我们将通过实现onRegisterPress方法来添加Firebase逻辑,以便在RegistrationScreen.js中使用电子邮件和密码创建新帐户:

In the account creation flow above, we do a few important things:

在上面的帐户创建流程中,我们做一些重要的事情:

  • We call Firebase Auth’s createUserWithEmailAndPassword API (line 13), which creates a new account that will show up in Firebase Console -> Authentication table.

    我们调用Firebase Auth的createUserWithEmailAndPassword API(第13行),该API创建一个新帐户,该帐户将显示在Firebase控制台->身份验证表中。
  • If the account registration was successful, we also store the user data in Firebase Firestore (line 24). This is necessary for storing extra user information, such as full name, profile photo URL, and so on, which cannot be stored in the Authentication table.

    如果帐户注册成功,我们还将用户数据存储在Firebase Firestore中(第24行)。 这对于存储多余的用户信息(例如全名,个人资料照片URL等)是必需的,而这些信息无法存储在“验证”表中。
  • If registration was successful, we navigate to the Home Screen, by passing in the user object data as well.

    如果注册成功,我们也将通过传递用户对象数据导航到主屏幕。
  • If any error occurs, we simply show an alert with it. Errors can be things such as no network connection, password too short, email invalid, and so on.

    如果发生任何错误,我们只需显示一个警报。 错误可能是诸如没有网络连接,密码太短,电子邮件无效等。

Reload your app and test the registration. If you successfully created one account, check that it shows up in Firebase Console -> Authentication:

重新加载您的应用并测试注册。 如果您成功创建了一个帐户,请检查该帐户是否显示在Firebase控制台 -> 身份验证中 :

6. React Native Firebase-登录 (6. React Native Firebase — Login)

Now that we are able to create new accounts, let’s implement the login functionality. Firebase SDK takes care of all the authorization and authentication steps needed for a secure login.

现在我们已经可以创建新帐户了,让我们实现登录功能。 Firebase SDK负责安全登录所需的所有授权和身份验证步骤。

Open LoginScreen.js, import firebase and complete the onLoginPress method:

打开LoginScreen.js ,导入firebase并完成onLoginPress方法:

Reload your app and go ahead and login with an existing account. The app should take you to the home screen if the credentials were correct, or it will alert you with an error if anything went wrong.

重新加载您的应用程序,然后继续并使用现有帐户登录。 如果凭据正确,则该应用程序应带您进入主屏幕,否则,如果出现任何问题,它将提示您错误。

7.坚持登录凭证 (7. Persist Login Credentials)

You’ll notice that if you quit the app and open it again, it will show the login screen again. For a good user experience, we’d want to land all logged in users on the Home screen. No one wants to type in their login credentials every time they want to use an app.

您会注意到,如果退出该应用程序并再次打开它,它将再次显示登录屏幕。 为了获得良好的用户体验,我们希望将所有已登录用户登录到主屏幕。 没人希望每次使用应用程序时都输入登录凭据。

This is also known as persistent login. Fortunately, Firebase SDK takes care of this for us, dealing with all the security concerns. Persistent login is enabled by default in Firebase, so all we need to do is fetch the currently logged in user.

这也称为永久登录。 幸运的是,Firebase SDK为我们处理了所有安全问题。 Firebase默认启用永久登录,因此我们要做的就是获取当前登录的用户。

Open App.js and let’s implement the persistent login feature:

打开App.js ,让我们实现持久登录功能:

onAuthStateChanged returns the currently logged in user. We then fetch all the extra user data that we stored in Firestore, and set it on the current component’s state. This will re-render the app component, which will display the Home screen.

onAuthStateChanged返回当前登录的用户。 然后,我们获取存储在Firestore中的所有其他用户数据,并将其设置为当前组件的状态。 这将重新渲染应用程序组件,这将显示主屏幕。

Notice how we call this the first time the app loads by leveraging the useEffect hook.

请注意,通过利用useEffect挂钩,我们在应用程序首次加载时如何称呼它。

8.从Firebase Firestore写入和读取数据 (8. Writing and Reading Data from Firebase Firestore)

We’ve already used Firestore above, for saving extra information on our users (the full name). In this dedicated section, we’re going to see how we can write data to Firestore, and how we can query it.

上面我们已经使用Firestore来保存有关用户的额外信息(全名)。 在本专用部分中,我们将了解如何将数据写入Firestore,以及如何查询数据。

We’ll also cover how to observe (listen to) changes in the Firestore collection and have those be reflected on the screen, in real-time. These can be very helpful in real-time apps, such as a React Native Chat.

我们还将介绍如何观察(侦听)Firestore集合中的更改并将这些更改实时反映在屏幕上。 这些在实时应用程序(例如React Native Chat)中非常有用。

To simplify, we are going to save some text items into a Firestore collection named “entities”. Think of these as tasks, posts, tweets, anything you want. We’ll create a simple file that adds a new entity and we’ll also list all the entities that belong to the currently logged in user. Additionally, the list will be updated in real-time.

为简化起见,我们将一些文本项保存到名为“实体”的Firestore集合中。 将它们视为任务,帖子,推文或任何您想要的东西。 我们将创建一个添加新实体的简单文件,还将列出属于当前登录用户的所有实体。 此外,该列表将实时更新。

  • Implement HomeScreen.js by rewriting it to the code below

    通过将其重写为下面的代码来实现HomeScreen.js

  • Style the home screen, by overriding HomeScreen/styles.js to:

    通过将HomeScreen / styles.js重写为以下内容来设置主屏幕的样式:

  • Reload the app and observe the new home screen. Type in some text and press the Add button

    重新加载该应用程序并观察新的主屏幕。 输入一些文字,然后按添加按钮

  • Nothing happened.

    什么都没有发生。
  • Create an index on the entities Firestore collection

    在实体Firestore集合上创建索引

You’ll notice that the list of entities is not rendered. If you check out the logs, you’ll see an warning about “The query requires an index”, followed by a long URL:

您会注意到没有显示实体列表。 如果您查看日志,则会看到有关“查询需要索引”的警告,后跟一个较长的URL:

This informs us that we can’t query the entities table by authorID and sort the data by createdAt in descending order, unless we create an index. Creating an index is actually really easy — simply click on that URL and then click the button:

这告诉我们,我们不能用的AuthorID和排序的数据通过createdAt降序排列查询实体表,除非我们创建一个索引。 创建索引实际上非常简单-只需单击该URL,然后单击按钮:

  • Reload the app again

    再次重新加载应用

Now everything works as expected:

现在一切都按预期工作:

  • The app lists all the entities in the entities collection, in descending creation order

    该应用程序以降序创建顺序列出了实体集合中的所有实体
  • Adding a new entity works fine

    添加新实体效果很好
  • The list updates in real-time (try deleting an entry directly in the database, or adding a new one directly from the app)

    列表实时更新(尝试直接在数据库中删除一项,或直接从应用程序中添加新项)

This is how your Firestore database looks like now:

这是您的Firestore数据库现在的样子:

This is how you read and write from Firestore in React Native. Let’s move forward to the last section.

这就是您在React Native中从Firestore读写的方式。 让我们继续上一节。

Play around with the app, by adding new entities. This is the final project:

通过添加新实体来玩这个应用程序。 这是最终项目:

结论 (Conclusion)

Firebase makes it really easy to add authentication and database support to any React Native app. Firebase SDK is extremely powerful, supporting a lot of common reading and writing database patterns.

Firebase使向任何React Native应用程序添加身份验证和数据库支持变得非常容易。 Firebase SDK非常强大,支持许多常见的读写数据库模式。

In addition to React Native, Firebase SDK provides support for a lot of other languages, such as Swift, Kotlin or Flutter. Check out those links for similar Firebase starter kits in various languages.

除React Native之外,Firebase SDK还支持许多其他语言,例如SwiftKotlinFlutter 。 请查看这些链接,以获取各种语言的类似Firebase入门套件。

We’ve showcased the most basic ones in this React Native Firebase tutorial. In the next series, we’ll cover more advanced features, such as Firebase Storage (file upload) and push notifications.

在此React Native Firebase教程中,我们展示了最基本的内容。 在下一个系列中,我们将介绍更多高级功能,例如Firebase存储(文件上传)和推送通知。

If you liked this tutorial, please give me a star on the Github repo and share this with your community. You can check out even more free React Native projects on Instamobile. Cheers!

如果您喜欢本教程,请给我一个Github存储库上的星星,并与您的社区分享。 您可以在Instamobile上查看更多免费的React Native项目 。 干杯!

翻译自: https://www.freecodecamp.org/news/react-native-firebase-tutorial/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: