React Native集成Firebase

這篇文章很詳細(xì)的介紹了從創(chuàng)建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>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市蔗崎,隨后出現(xiàn)的幾起案子酵幕,更是在濱河造成了極大的恐慌扰藕,老刑警劉巖缓苛,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件日月,死亡現(xiàn)場離奇詭異蜂绎,居然都是意外死亡拨脉,警方通過查閱死者的電腦和手機(jī)解阅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門男公,熙熙樓的掌柜王于貴愁眉苦臉地迎上來倾哺,“玉大人檬某,你說我怎么就攤上這事喧半。” “怎么了?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長拯刁。 經(jīng)常有香客問我乏悄,道長赴邻,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任猪狈,我火速辦了婚禮米辐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘跺株。我一直安慰自己复濒,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布乒省。 她就那樣靜靜地躺著巧颈,像睡著了一般。 火紅的嫁衣襯著肌膚如雪袖扛。 梳的紋絲不亂的頭發(fā)上砸泛,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天,我揣著相機(jī)與錄音蛆封,去河邊找鬼唇礁。 笑死,一個胖子當(dāng)著我的面吹牛惨篱,可吹牛的內(nèi)容都是我干的垒迂。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼妒蛇,長吁一口氣:“原來是場噩夢啊……” “哼机断!你這毒婦竟也來了楷拳?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤吏奸,失蹤者是張志新(化名)和其女友劉穎欢揖,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體奋蔚,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡她混,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了泊碑。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片坤按。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖馒过,靈堂內(nèi)的尸體忽然破棺而出臭脓,到底是詐尸還是另有隱情,我是刑警寧澤腹忽,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布来累,位于F島的核電站,受9級特大地震影響窘奏,放射性物質(zhì)發(fā)生泄漏嘹锁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一着裹、第九天 我趴在偏房一處隱蔽的房頂上張望领猾。 院中可真熱鬧,春花似錦骇扇、人聲如沸瘤运。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽拯坟。三九已至,卻和暖如春韭山,著一層夾襖步出監(jiān)牢的瞬間郁季,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工钱磅, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留梦裂,地道東北人。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓盖淡,卻偏偏與公主長得像年柠,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子褪迟,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,871評論 2 354