firebase api

    科技2025-03-18  22

    firebase api

    Hello everyone! Today’s article will be a beginner’s introduction to React Context API, as I noticed that this concept is quite complex for React beginners to grasp. And I’ll use Firebase Authentication to demonstrate the beauty of using React Context API. Let’s begin!

    大家好! 今天的文章将是React Context API的初学者介绍,因为我注意到对于React初学者来说,这个概念相当复杂。 我将使用Firebase身份验证来演示使用React Context API的好处。 让我们开始!

    Some prerequisites to follow this tutorial:

    遵循本教程的一些先决条件:

    Basic understanding of React (i.e. props, state, etc.)

    对React的基本了解(即道具,状态等) Little understanding of Firebase (but more knowledge will help)

    对Firebase的了解很少(但更多的知识会有所帮助)

    什么是React Context API? (What’s React Context API?)

    Normally in React we pass something called props from the Parent component to its Children components. A React app consists of components, many have Parent-Child relationships and therefore a simple visualization of an app can look like:

    通常,在React中,我们将名为props东西从Parent组件传递给子组件。 React应用程序由组件组成,许多组件具有父子关系,因此应用程序的简单可视化如下所示:

    Most of the time, we only need to pass from Parent to Child so using the usual state and props is good enough. But what if we need to pass a prop to lots of components? Even those deeply nested or on another tree?

    大多数时候,我们只需要从父级传递到子级,因此使用通常的state和props就足够了。 但是,如果我们需要将prop传递给许多组件怎么办? 甚至那些深深嵌套或在另一棵树上?

    Examples of such props would be:

    此类props示例如下:

    The user’s preferred language

    用户的首选语言 The theme or color scheme of the app the user has selected

    用户选择的应用程序的主题或配色方案The authenticated user’s properties

    经过身份验证的用户的属性

    In such cases, having to pass the prop manually from and to each component would be too tedious! This is called prop drilling. So here comes React Context API to the rescue. According to their official documentation,

    在这种情况下,必须手动将prop从一个组件传递到prop组件,这太麻烦了! 这称为支撑钻。 因此,React Context API来了。 根据他们的官方文件,

    React Context API provides the ability to pass props to child components without needing to pass them down manually.

    React Context API提供了将prop传递给子组件的功能,而无需手动传递它们。

    There, so now we know what it is and when we need to use it.

    在那里,所以现在我们知道它是什么以及何时需要使用它。

    I shall now present a simple example using Firebase Authentication. We need to use the Context API, so we don’t have to manually pass the authenticated user props to every child component. Let’s see how this works.

    我现在将介绍一个使用Firebase Authentication的简单示例。 我们需要使用Context API,因此我们不必手动将经过身份验证的用户道具传递给每个子组件。 让我们看看它是如何工作的。

    第1步:创建Firebase项目 (Step 1: Create a Firebase project)

    Head over to firebase.google.com and create a new project.

    转到firebase.google.com并创建一个新项目。

    On the dashboard, click on the Web icon to initialize Firebase for Web Apps.

    在仪表板上,单击Web图标以初始化Web Apps的Firebase。

    Follow the steps by Firebase and you’ll reach a page that shows your config variables. This is important so copy and save it somewhere. We will use it soon.

    按照Firebase的步骤进行操作,您将到达一个显示配置变量的页面。 这很重要,因此请复制并将其保存在某处。 我们将尽快使用它。

    第2步:设置Firebase身份验证 (Step 2: Set up Firebase Authentication)

    Head over to Authentication as shown in the image below.

    转到认证,如下图所示。

    Then, you can set the sign-in methods for app. For my example, I’ll enable Google, Email and Facebook.

    然后,您可以设置应用程序的登录方法。 在我的示例中,我将启用Google,电子邮件和Facebook。

    Facebook登录设置 (Facebook Sign-in Set Up)

    For Google and Email authentication, you simply have to press the toggle button to enable it as a sign-in method. For Facebook, you’ll need to have a Facebook Developers account to set it up.

    对于Google和电子邮件身份验证,您只需按切换按钮即可将其启用为登录方法。 对于Facebook,您需要拥有一个Facebook Developers帐户才能进行设置。

    This is optional, so please skip to step 3 if you don’t plan on using Facebook as an authentication method.

    这是可选的,因此如果您不打算使用Facebook作为身份验证方法,请跳至步骤3。

    Head to developers.facebook.com and create a developer account

    前往developers.facebook.com并创建一个开发者帐户

    Then create a new project and you will see this page. Go to Settings > Basic. Copy your App ID and App Secret.

    然后创建一个新项目,您将看到此页面。 转到设置>基本。 复制您的App ID和App Secret。

    Now go back to Firebase and paste them accordingly. At the same time, copy the url as shown in the image below.

    现在回到Firebase并相应地粘贴它们。 同时,复制URL,如下图所示。

    Back at Facebook for Developers, under ‘Add a Product’, find a product called Facebook Login and click the ‘Set Up’ button.

    回到Facebook for Developers,在“添加产品”下找到一个名为“ Facebook登录”的产品,然后单击“设置”按钮。

    Paste the url you copied from Firebase to the field shown in the image below and click ‘Save Changes’.

    将您从Firebase复制的网址粘贴到下图所示的字段中,然后单击“保存更改” 。

    Finally, head to Facebook Login > Quickstart and enter the url of your website. In my case, this is only a test app so the url is http://localhost:3000. Click 'Save' and you are done!

    最后,转到Facebook登录>快速入门,然后输入您的网站的网址。 就我而言,这只是一个测试应用程序,因此URL为http://localhost:3000 。 点击“保存” ,您就完成了!

    Your users can now use Facebook to authenticate themselves into your app.

    您的用户现在可以使用Facebook来对自己的应用程序进行身份验证。

    第三步:设置React项目 (Step 3: Set up React Project)

    With our Firebase Authentication done for our 3 sign-in methods (i.e. Google, Email and Facebook), let’s set up our React project to be able to use Firebase.

    通过针对3种登录方法(即Google,Email和Facebook)的Firebase身份验证完成后,让我们将React项目设置为能够使用Firebase。

    In the root directory of our project, run:

    在我们项目的根目录中,运行:

    npm install firebase react-firebaseui

    firebase contains the tools and infrastructure you need to set up firebase in the React app.

    firebase包含在React应用程序中设置firebase所需的工具和基础设施。

    react-firebaseui provides pre-made components to handle and display authentication easily.

    react-firebaseui提供了可轻松处理和显示身份验证的预制组件。

    第4步:Firebase配置 (Step 4: Firebase config)

    Create a ‘Firebase’ folder in the React App’s src folder and inside it, create a file named config.js. This is where we will paste our config variables from Step 1. If you forgot to copy it, you can always find your config variables from your Firebase project settings (see image below).

    在React App的src文件夹中创建一个“ Firebase”文件夹,并在其中创建一个名为config.js的文件。 在这里,我们将粘贴第1步中的配置变量。如果您忘记复制它,则始终可以从Firebase项目设置中找到配置变量(请参见下图)。

    In Firebase/config.js, we will do 3 things:

    在Firebase/config.js ,我们将做三件事:

    Import dependencies

    导入依赖

    Use firebase.initializeApp(config) to create a Firebase app instance

    使用firebase.initializeApp(config)创建Firebase应用程序实例

    Export this app for use in which we will see soon

    导出此应用程序以供使用,我们很快就会在其中使用

    In code, it should look like:

    在代码中,它应类似于:

    //1. import the dependenciesimport * as firebase from "firebase";import "firebase/auth";//2. Initialize app with the config varsconst app = firebase.initializeApp({ apiKey: process.env.REACT_APP_API_KEY, authDomain: process.env.REACT_APP_AUTH_DOMAIN, databaseURL: process.env.REACT_APP_DATABASE_URL, projectId: process.env.REACT_APP_PROJECT_ID, storageBucket: process.env.REACT_APP_STORAGE_BUCKET, messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,});//3. export it for useexport default app;

    第5步:Firebase上下文 (Step 5: Firebase context)

    Now let’s use the Context API to create a Firebase context. In the Firebase folder, add a new file called context.js.

    现在,让我们使用Context API创建Firebase上下文。 在Firebase文件夹中,添加一个名为context.js的新文件。

    We will do the following:

    我们将执行以下操作:

    Import React dependencies and the app from config.js

    从config.js导入React依赖项和应用

    Create and export a React context called AuthContext using React.createContext()

    使用React.createContext()创建和导出一个称为AuthContext的React上下文

    Create and export AuthProvider which contains a React Context Provider.

    创建并导出包含React Context Provider的AuthProvider 。

    Every Context object has a Provider that allows other components to consume its context. In this case, our AuthProvider will provide the state of user to other components. This is so that any component in our app can determine whether a user has signed in and access the user's properties.

    每个Context对象都有一个Provider ,它允许其他组件使用其上下文。 在这种情况下,我们的AuthProvider将user的状态提供给其他组件。 这样我们的应用程序中的任何组件都可以确定用户是否已登录并访问该用户的属性。

    The user state is initialized as null with the useState hook and is updated using the useEffect hook and Firebase's auth().onAuthStateChanged(setUser).

    user状态使用useState挂钩初始化为null,并使用useEffect挂钩和Firebase的auth().onAuthStateChanged(setUser) 。

    The onAuthStateChanged is basically an observer that listens for a change in authentication. That way, whenever a user signs in or out, our user state will be automatically updated in our AuthProvider.

    onAuthStateChanged基本上是一个侦听器,用于侦听身份验证中的更改。 这样,无论何时用户AuthProvider或注销,我们的user状态都会在AuthProvider自动更新。

    Here’s what the code looks like:

    代码如下所示:

    //1.import React, { useEffect, useState } from "react";import app from "./config";//2.export const AuthContext = React.createContext();//3.export const AuthProvider = ({ children }) => { const [user, setUser] = useState(null); useEffect(() => { app.auth().onAuthStateChanged(setUser); }, []); return ( <AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider> );};

    步骤6:将AuthProvider导入App.js (Step 6: Import AuthProvider to App.js)

    Now, we can import AuthProvider to App.js and place all components inside it. This way, it can pass the context to any component in the app (because it is the top node of the component tree).

    现在,我们可以导入AuthProvider到App.js并把它里面的所有组件。 这样,它可以将上下文传递到应用程序中的任何组件(因为它是组件树的顶部节点)。

    import { AuthProvider } from "./Firebase/context";function App() { return ( <AuthProvider> <Router> <div className="App"> <Nav /> <Switch> <Route path="/signin" exact component={SignIn} /> </Switch> </div> </Router> </AuthProvider> );}

    步骤7:登录组件 (Step 7: Sign In Component)

    We create a SignIn.js that displays the sign in buttons for the user to log in to our app. As you can see from the App.js code above, my app will render the sign in component at the path /signin.

    我们创建一个SignIn.js ,显示登录按钮供用户登录我们的应用程序。 从上面的App.js代码可以看到,我的应用程序将在路径/signin signin处呈现登录组件。

    There is a “Sign In/ Register” button in the Nav component which links to the /signin path when clicked, to display the sign in buttons. We will look at our Nav.js after this.

    Nav组件中有一个“登录/注册”按钮,单击该按钮可链接到/signin路径,以显示登录按钮。 之后,我们将看一下Nav.js。

    So our sign in component will import the following:

    因此,我们的登录组件将导入以下内容:

    import React, { useContext } from "react";import "../App.css";import firebase from "firebase";import { FirebaseAuth } from "react-firebaseui";import { AuthContext } from "../Firebase/context";import { Redirect } from "react-router-dom";

    useContext is a React hook which allows the component to consume the context.

    useContext是一个React挂钩,它允许组件使用上下文。

    FirebaseAuth is the styled component for our sign in methods

    FirebaseAuth是我们登录方法的样式化组件

    AuthContext contains our context which will be consumed by useContext

    AuthContext包含我们的上下文,该上下文将由useContext

    Redirect allows us to redirect the user to the home page once the sign in is successful

    Redirect使我们能够在登录成功后将用户重定向到主页

    Below our import statements, we’ll have:

    在导入语句下方,我们将有:

    export default function SignIn() { //get the user state from the context const { user } = useContext(AuthContext); //this is our config for FirebaseAuth const uiConfig = { signInFlow: "popup", signInOptions: [ firebase.auth.GoogleAuthProvider.PROVIDER_ID, firebase.auth.FacebookAuthProvider.PROVIDER_ID, firebase.auth.EmailAuthProvider.PROVIDER_ID, ], callbacks: { signInSuccess: () => false, }, };//if user exists or signed in, we redirect the page to home, else display the sign in methods with FirebaseAuth return ( <div> {!!user ? ( <Redirect to={{ pathname: "/" }} /> ) : ( <div> <p>Please Sign In</p> <FirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()} /> </div> )} </div> );}

    Finally, we make our Nav component to show a sign in button if there's no user currently authenticated. If a user does exists, we shall display their name and picture by accessing the user's displayName and photoURL properties. More user properties can be found in the docs here.

    最后,如果当前没有经过身份验证的用户,则使Nav组件显示登录按钮。 如果确实存在,我们将通过访问用户的displayName和photoURL属性来显示其名称和图片。 在此处的文档中可以找到更多的用户属性。

    Also, we will have a ‘Sign out’ Link that executes app.auth().signOut() when clicked to sign the user out.

    另外,我们将具有一个“注销”链接,单击该链接可执行app.auth().signOut()来注销用户。

    Here’s our Nav.js:

    这是我们的Nav.js :

    import { AuthContext } from "../Firebase/context.js";export default function Nav() { //get the user state from context const { user } = useContext(AuthContext);//if user exists, display user name and picture.//else, show a sign in button instead return ( <div className="account"> {!!user ? ( <div className="dropdown"> <p>{`Welcome, ${user.displayName}`}</p> <div className="dropdown-content"> <Link to="/">Create Stories</Link> <Link to="/">My Stories</Link> <Link onClick={() => app.auth().signOut()}>Sign Out</Link> </div> </div> ) : ( <Link to="/signin"> <button>SIGN IN/ REGISTER</button> </Link> )} </div> );}

    我们的最终结果 (Our Final Result)

    In conclusion, the React Context API provides a beautiful and simple way to create context to pass data to other components in your app. I hope this article has been helpful to learning how to use the Context API as well as Firebase Authentication. Thanks so much for reading. Please leave any questions or comments below. Optionally, read the resources below to learn more about what we discuss today. Till next time, cheers!

    总之,React Context API提供了一种美丽而简单的方法来创建上下文,以将数据传递到应用程序中的其他组件。 希望本文对学习如何使用Context API和Firebase身份验证有所帮助。 非常感谢您的阅读。 请在下面留下任何问题或评论。 (可选)阅读下面的资源以了解有关我们今天讨论的内容的更多信息。 直到下一次,加油!

    进一步阅读 (Further Reading)

    React Context API Documentation

    React Context API文档

    Firebase for Web Apps Documentation

    Web应用程序的Firebase文档

    Originally published at https://lo-victoria.com.

    最初发布在https://lo-victoria.com 。

    普通英语JavaScript (JavaScript In Plain English)

    Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

    喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容!

    翻译自: https://medium.com/javascript-in-plain-english/introduction-to-react-context-api-with-firebase-authentication-92a6a3cf116d

    firebase api

    相关资源:Go-Packagefirebase提供一个Firebasev3.0.0API实现
    Processed: 0.013, SQL: 8