React Native集成Firebase

这篇文章很详细的介绍了从创建RN工程开始的集成过程,记录在此是为了方便日后查阅,也希望能够提供给相同需求的人一些帮助,毕竟要访问原文需要一些“手段”。不说废话,上原文

December 05, 2018

Integrating Firebase with React Native

by Aman Mittal
Integrating Firebase with React Native

Firebase is a Backend as a Service (BaaS) that provides an advantage to mobile developers who use React Native for developing mobile applications. As a React Native developer, by using Firebase you can start building an MVP (minimum viable product), keeping the costs low and prototyping the application pretty fast.

In this tutorial, we will be learning how to get started by integrating Firebase with a React Native application. We will also create a small application from scratch with the help of Firebase & React Native to see how they work together.

Getting Started

Firebase is a platform that got acquired by Google and has a healthy and active community. Most users in this community are web and mobile developers as Firebase can help with mobile analytics, push notification, crash reporting and out of the box provides email as well as social authentication.

To get started, you will need a target mobile OS, whether you choose to go with iOS or Android or both. Please refer to React Native official documentation if you are setting up React Native development environment for the first time. You will need sdk tools and Android Studio especially to setup a developer environment for Android. For iOS, you only need Xcode installed on your macOS. You will also need to have:

React Native is distributed as two npm packages, react-native-cli, and react-native. We are going to use the react-native-cli to generate an app. Begin by installing react-native-cli:

npm install -s react-native-cli

Now, let’s create a new React Native project called “rnFirebaseDemo”:

react-native init rnFirebaseDemo

When the above command is done running, traverse into the project directory using cd rnFirebaseDemo. Now, let’s check if everything is working correctly and our React Native application has been properly initialized by running one of the following commands:

# on macOS
react-native run-ios

# For Windows/Unix users
react-native run-android

This command will run the default screen as shown below in an iOS simulator or Android emulator but it will take a few moments since we are running it for the first time.

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
React Native App Default Screen

</center>

Adding Firebase

To add Firebase to our existing React Native application, we need to install the dependency.

yarn add firebase

When we open the project in a code editor, its structure looks like this:

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
React Native App Structure

</center>

We need to make some modifications before we can really start building our app. Create an src directory inside the root folder. This is where our app components and screens will live. Further, within the src directory, we will create two folders: screens and components.

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
React Native App src Directory

</center>

The screen directory will contain all the UI related components that we need to display to the end user, whereas the components folder will contain any other component that will be used or re-used to display the user interface.

Let us create our first screen, Home screen, inside screens/ with a new file Home.js.

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class Home extends Component {
  render() {
    return (
      <View>
        <Text>Home Screen</Text>
      </View>
    );
  }
}

Our next screen is going to be Add Item. Create a new file called AddItem.js.

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class AddItem extends Component {
  render() {
    return (
      <View>
        <Text>Add Item</Text>
      </View>
    );
  }
}

Our last screen is going to be a List of items that we need to display. In the same directory, create a new file called List.js.

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class List extends Component {
  render() {
    return (
      <View>
        <Text>List</Text>
      </View>
    );
  }
}

Adding react-navigation

To navigate between different screens, we need to add the react-navigationlibrary. We are going to use the latest version that is 3.0.0.

yarn add react-navigation

Next, we will install react-native-gesture-handler. If you’re using Expo, you don’t need to do anything here.

yarn add react-native-gesture-handler

The next step is clearly to run the command below and link the libraries we just installed:

react-native link

After adding this package, let us run the build process again:

# on macOS
react-native run-ios

# For Windows/Unix users
react-native run-android

Now, to see it in action, let us add the Home component as our first screen. Add the following code in App.js.

import React, { Component } from 'react';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import Home from './src/screens/Home';

// we will use these two screens later in our AppNavigator
import AddItem from './src/screens/AddItem';
import List from './src/screens/List';

const AppNavigator = createStackNavigator({
  Home: {
    screen: Home
  }
});

const AppContainer = createAppContainer(AppNavigator);

export default class App extends Component {
  render() {
    return <AppContainer />;
  }
}

At this stage, if we go to the simulator, we will see the following result:

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
React Native App Home Screen

</center>

The Home Screen is showing up. We will add two other screens as routes to AppNavigator in order to navigate to them through the Home Screen.

const AppNavigator = createStackNavigator(
  {
    Home,
    AddItem,
    List
  },
  {
    initialRouteName: 'Home'
  }
);

Now, our stack has three routes: a Home route, an AddItem route, and a ListItem route. The Home route corresponds to the Home screen component, the AddItem corresponds to the AddItem screen and the ListItem route corresponds to the ListItem component. The initial route for the stack is the Home route, this is defined if we have multiple screens and need to describe a starting point.

Navigating between the screens

Previously, we defined a stack navigator with three routes but we didn't hook them up in order to navigate between them. Well, this is an easy task too. The react-navigation library provides us with a way to manage navigation from one screen to another and back. To make this work, we will modify the Home.js.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

export default class Home extends Component {
  render() {
    return (
      <View>
        <Text>Home Screen</Text>
        <Button
          title="Add an Item"
          onPress={() => this.props.navigation.navigate('AddItem')}
        />
        <Button
          title="List of Items"
          color="green"
          onPress={() => this.props.navigation.navigate('List')}
        />
      </View>
    );
  }
}

In the code above, we are adding a Button component from the react-native API. react-navigation passes a navigation prop in the form of this.props.navigation to every screen in the stack navigator. We have to use the same screen name on the onPress function to navigate as we defined in App.jsunder AppNavigator.

You can also customize the back button manually with your own styling on both screens AddItem and List but, for our demonstration, we are going to use the default.

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
React Native App Navigation

</center>

Creating a Database with Firebase

Go to the Firebase Console, log in from your Google Account and a create a new project.

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
Firebase New Project

</center>

We will then add the database configuration in a new file inside src/config.js.

import Firebase from 'firebase';
let config = {
  apiKey: 'AIzaXXXXXXXXXXXXXXXXXXXXXXX',
  authDomain: 'rnfirebXXX-XXXX.firebaseapp.com',
  databaseURL: 'rnfirebXXX-XXXX.firebaseapp.com',
  projectId: 'rnfirebase-XXXX',
  storageBucket: 'rnfirebase-XXXX.appspot.com',
  messagingSenderId: 'XXXXXXX'
};
let app = Firebase.initializeApp(config);
export const db = app.database();

The config object is where you fill in the details you get after creating a new project in Firebase and going to the section Add Firebase to your web app. Also in the Firebase console, from left sidebar, click on Database and then choose the first option: ((Realtime Database)). Then, go to “rules” and paste the following:

{ "rules": { ".read": true, ".write": true } }

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
Firebase Database Rules

</center>

Adding Data from the App to Firebase

In this section, we will edit AddItem.js which represents an input field and a button. The user can add a item to the list and it will get saved to Firebase data.

import React, { Component } from 'react';
import {
  View,
  Text,
  TouchableHighlight,
  StyleSheet,
  TextInput,
  AlertIOS
} from 'react-native';

import { db } from '../config';

let addItem = item => {
  db.ref('/items').push({
    name: item
  });
};

export default class AddItem extends Component {
  state = {
    name: ''
  };

  handleChange = e => {
    this.setState({
      name: e.nativeEvent.text
    });
  };
  handleSubmit = () => {
    addItem(this.state.name);
    AlertIOS.alert('Item saved successfully');
  };

  render() {
    return (
      <View style={styles.main}>
        <Text style={styles.title}>Add Item</Text>
        <TextInput style={styles.itemInput} onChange={this.handleChange} />
        <TouchableHighlight
          style={styles.button}
          underlayColor="white"
          onPress={this.handleSubmit}
        >
          <Text style={styles.buttonText}>Add</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    padding: 30,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#6565fc'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center'
  },
  itemInput: {
    height: 50,
    padding: 4,
    marginRight: 5,
    fontSize: 23,
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 8,
    color: 'white'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor: 'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

In the code above, we are adding a Firebase database instance from config.js and db and then pushing any item that the user adds through addItem and handleSubmit(). You will get an alert message when you press the button Add to add the item from the input value as shown below.

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
React Native App Pushing to Firebase

</center>

To verify that the data is there in the database, go to your Firebase console.

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
Firebase Pushed Data

</center>

Fetching Items from the Database

To fetch data from the Firebase database, we are going to use the same reference to db in List.js.

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import ItemComponent from '../components/ItemComponent';

import { db } from '../config';

let itemsRef = db.ref('/items');

export default class List extends Component {
  state = {
    items: []
  };

  componentDidMount() {
    itemsRef.on('value', snapshot => {
      let data = snapshot.val();
      let items = Object.values(data);
      this.setState({ items });
    });
  }

  render() {
    return (
      <View style={styles.container}>
        {this.state.items.length > 0 ? (
          <ItemComponent items={this.state.items} />
        ) : (
          <Text>No items</Text>
        )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ebebeb'
  }
});

For the ItemComponent, we create a new file inside components/ItemComponent.js. This is a non-screen component. Only the List will use it to map and display each item.

import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';

export default class ItemComponent extends Component {
  static propTypes = {
    items: PropTypes.array.isRequired
  };

  render() {
    return (
      <View style={styles.itemsList}>
        {this.props.items.map((item, index) => {
          return (
            <View key={index}>
              <Text style={styles.itemtext}>{item.name}</Text>
            </View>
          );
        })}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  itemsList: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'space-around'
  },
  itemtext: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center'
  }
});

This step concludes the integration of a Firebase database with our React Native app. You can now add the new data items and fetch them from the database as shown below.

<center style="text-rendering: geometricprecision; box-sizing: border-box;">
React Native App Fetching from Firebase

</center>

Conclusion

In this tutorial, we’ve shown you how to integrate Firebase with a React Native application. You don’t a complete server that creates an API and further uses a database to prototype or build an MVP of your application.

You can find the complete code inside this Github repo. If you have any questions, you can ask the author directly by tweeting to @amanhimself.

Lastly, if you're building React Native apps with sensitive logic, be sure to protect them against code theft and reverse-engineering by following our guide.

</article>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335