React Native 开发

improve this page | report issue

请按照以下教程来开发 React Native 应用程序:设置开发环境、体验产品以及通过与 Mobile Foundation 8.0 产品集成来增加价值。

如果您是选择 React Native 作为移动或 Web 应用程序开发框架的开发人员,以下部分可帮助您在 React Native 应用程序中开始使用 IBM Mobile Foundation SDK。

您可以使用自己首选的代码编辑器(如 Atom.io、Visual Studio Code、Eclipse、IntelliJ 或任何其他编辑器)来编写自己的应用程序。

步骤 1:安装 React Native CLI

要开始进行 React Native 开发,所需执行的第一步是安装 React Native CLI

要安装 React Native CLI,请执行以下步骤:

下载并安装 NodeJS

从命令行窗口运行以下命令:

    npm install -g react-native-cli
   

遵循 React Native 文档中的“入门”页面中提供的指示信息来设置您的机器,以进行 React Native 开发。

这包括 Android 和 iOS 需要的设置。

步骤 2:设置 MobileFirst 开发环境

在您安装 React Native CLI 之后,设置 MobileFirst 开发环境。有关详细信息,请参阅教程设置 MobileFirst 开发环境以设置您的 MobileFirst 开发环境。


转至快速启动选项卡,以了解如何使用 React Native SDK 快速启动开发工作。

执行以下步骤,以在 MobileFirst Platform Foundation 上快速开始使用 React Native 进行开发。

该快速启动教程的目的是解释简单的端到端流程。

Github 中提供了样本应用程序,将下载样本并向 MobileFirst Server 注册。提供的适配器(或新适配器)将部署到 MobileFirst Operations Console。应用程序逻辑更改为发出资源请求。

预期结果:成功 ping MobileFirst Server,并使用适配器成功检索数据。

步骤 1:启动 MobileFirst Server

确保您已创建 Mobile Foundation 实例,如果要使用 MobileFirst Developer Kit,请浏览至服务器的文件夹并运行以下命令:./run.sh(在 Mac 和 Linux 中)或 run.cmd(在 Windows 中)。

步骤 2:添加 React Native SDK

步骤 2.1:Github 下载 React Native 样本应用程序。

步骤 2.2:将 React Native SDK 添加到下载的 React Native 样本应用程序

针对 React Native 的 MobileFirst SDK 可用作 NPM 中的 React Native 模块

  1. 浏览至已下载的 React Native 项目的根目录,然后添加 MobileFirst 核心 React Native 插件,将目录更改为 React Native 项目的根目录:cd MFPStarterReactNative
  2. 使用 NPM CLI 命令添加 MobileFirst 插件:npm install react-native-plugin-name
    例如:
            npm install react-native-ibm-mobilefirst --save
          
    上述命令会将 MobileFirst 核心 SDK 插件添加到 React Native 项目。
  3. 将所有本机依赖关系链接到您的应用程序
            react-native link
          

步骤 2.3:特定于其他平台的步骤

Android


将以下行添加到 AndroidManifest.xml ({project-folder}/android/app/src/main/)
      <![CDATA[
      <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/  package="com.myapp">
        ...
        <application tools:replace="android:allowBackup"
        ...
      </application>
    ]]>
    

iOS


在 XCode 中打开您的项目。在项目导航器中,从 ios 文件夹拖放 mfpclient.plist。

步骤 3:注册应用程序

  1. 打开命令行窗口并浏览至项目的特定平台(iOS 或 Android)的根目录。
            cd ios
          
            cd android
          
  2. 运行以下命令以注册应用程序:
            mfpdev app register
          

    如果使用的是远程服务器,请使用命令 mfpdev server add 进行添加。 mfpdev app register CLI 命令将先连接到 MobileFirst Server 以注册应用程序。每个平台将在 MobileFirst Server 中注册为应用程序。

    • iOS

      如果您的平台是 iOS,那么将请求您提供应用程序的 BundleID。要点:BundleID 是区分大小写的

      mfpdev app register CLI 命令将先连接到 MobileFirst Server 以注册应用程序,然后更新 Xcode 项目根目录的 mfpclient.plist 配置文件,其中包含标识 MobileFirst Server 的元数据。

      注:在 XCode 的项目导航器中,从 ios 文件夹拖放 mfpclient.plist。此步骤仅适用于 iOS 平台。

    • Android

      如果您的平台是 Android,那么将请求您提供应用程序的包名称。要点:包名称是区分大小写的

      mfpdev app register CLI 命令将先连接到 MobileFirst Server 以注册应用程序,之后在 Android Studio 项目的 [project root]/app/src/main/assets/ 文件夹中生成 mfpclient.properties 文件,然后向其添加用于标识 MobileFirst Server 的元数据。

步骤 4:编辑应用程序逻辑

  1. 在您所选的代码编辑器中打开 React Native 项目。
  2. WLAuthorizationManager 类导入 App.js
  3.          import {WLAuthorizationManager, WLResourceRequest} from 'react-native-ibm-mobilefirst';
             
  4. 选择位于项目根文件夹的 App.js 文件并粘贴以下代码片段,替换现有的 WLAuthorizationManager.obtainAccessToken() 函数:
    请参阅此处的 React Native 客户端 API 参考。
               WLAuthorizationManager.obtainAccessToken("").then(
                   (token) => {
                     console.log('-->  pingMFP(): Success ', token);
                     var resourceRequest = new WLResourceRequest("/adapters/javaAdapter/resource/greet/",
                       WLResourceRequest.GET
                     );
                     resourceRequest.setQueryParameters({ name: "world" });
                     resourceRequest.send().then(
                       (response) => {
                         // Will display "Hello world" in an alert dialog.
    
                         alert("Success: " + response.responseText);
                       },
                       (error) => {
                         alert("Failure: " + JSON.stringify(error));
                       }
                     );
                   }, (error) => {
                     console.log('-->  pingMFP(): failure ', error.responseText);
                     alert("Failed to connect to MobileFirst Server");
                   });
           

步骤 5:部署适配器

下载这一准备好的 .adapter 工件,并通过使用操作 → 部署适配器操作从 MobileFirst Operations Console 进行部署。

步骤 5.1:选择操作 → 下载样本选项。下载 Hello World Java 适配器样本

或者,单击适配器旁边的新建按钮。

如果未安装 Maven 和 MobileFirst CLI,请遵循屏幕上的设置开发环境指示信息。

步骤 5.2:命令行窗口中,导航至适配器的 Maven 项目根文件夹并运行以下命令:

    mfpdev adapter build
  

步骤 5.3:在构建完成时,使用操作 → 部署适配器操作从 MobileFirst Operations Console 进行部署。适配器可在 [adapter]/target 文件夹中找到。

步骤 6:测试应用程序

使用以下命令运行应用程序:

     react-native run-ios|run-android
    

如果已连接某设备,将在该设备上安装并启动此应用程序。否则,将使用模拟器或仿真器。

有关快速启动步骤的详细指示信息,请参阅此处

结果

  • 单击 Ping MobileFirst Server 按钮将显示已连接到 MobileFirst Server
  • 如果应用程序能够连接到 MobileFirst Server,那么将使用部署的 Java 适配器进行资源请求调用。然后,适配器响应将显示在警报中。

React Native SDK for IBM MobileFirst JSONStore

IBM Mobile Foundation JSONStore 是一个可选的客户机端 API,提供轻量级、面向文档的存储系统。JSONStore 支持持久存储 JSON 文档。即使设备处于脱机状态,在 JSONStore 中也可以使用应用程序中的文档。这种持久的、始终可用的存储很有用,例如,当设备中没有可用的网络连接时,使用户能够访问文档。

安装

针对 React Native 应用程序的 IBM MobileFirst JSONStore SDK 依赖于 IBM MobileFirst Foundation SDK。将 IBM MobileFirst Foundation SDK 添加到您的应用程序。

浏览至 React Native 应用程序的文件夹,然后运行以下命令来安装针对 React Native 应用程序的 JSONStore SDK。

      npm install react-native-ibm-mobilefirst-jsonstore --save
      
受支持的平台为 Android 和 iOS。

入门

先决条件

创建 React Native 项目

  1. 第一步是创建 React Native 项目。让我们将应用程序称为 JSONStoreApp。使用 React Native CLI 创建新项目。
          react-native init JSONStoreApp
          cd JSONStoreApp
          
  2. 安装 MobileFirst 核心 SDK 并完成入门指示信息
  3. 将 IBM MobileFirst JSONStore SDK 添加到您的应用程序。
          npm install react-native-ibm-mobilefirst-jsonstore —-save
          
  4. 链接您的项目,以便将所有本机依赖关系添加到您的 React Native 项目。
          react-native link
          

配置您的 Android 应用程序

  • 将以下行添加到 /android/app/build.gradleandroid 部分:
        packagingOptions{
        	exclude 'META-INF/ASL2.0'
        }
        

创建 JSONStore 集合

使用 JSONStore API 的第一步是创建 JSONStore 集合。

  1. 将 JSONStore 类导入您的应用程序。打开 App.js 并在其他导入语句中添加以下行:
        import {WLJSONStore, JSONStoreCollection} from 'react-native-ibm-mobilefirst-jsonstore';
        
  2. 创建并打开集合。您可以同时打开多个集合。针对诸如使用密码保护您的集合、设置同步策略等高级选项,传递 JSONStoreInitOptions 参数:
        var dogs = new JSONStoreCollection('dogs');
        WLJSONStore.openCollections(['dogs']);  // Provide the name of the collection as a string.
    
        

将数据添加到集合

将 JSON 数据添加到您的集合。

    	var hachi = { "name" : "Hachiko" , "breed" : "Akita" , "country" : "Japan"};
        dogs.addData(hachi).then( ()=> {
          // Data was added to the collection successfully.

        }).catch ( (err) => {
          // Error adding data. See the err object for more information on the error

        })
    

从集合查询数据

使用任何 JSONStoreCollection.find* API 查询集合。使用 JSONStoreQueryPart 和 JSONStoreQuery API 对 JSON 数据进行高级过滤和查询。

    	dogs.findAllDocuments().then( (result) => {
           // result will have all the documents in the collection

           // E.g. [ {"json": {"name":"Hachiko","breed":"Akita","country":"Japan"},"_id":2}]

         }).catch((error) => {
            console.error ("Error finding docs " +  JSON.stringify(error));
         });
    

关闭、清除和销毁您的集合。

关闭您的集合将关闭您的 JSONStore 集合,要进一步访问,需要使用 openCollections API 重新将其打开。

    WLJSONStore.closeAll()
    

清除集合将从集合中移除所有文档,但不会将其销毁。

    	dogs.clearCollection().then (()=>{
    		// All documents cleared successfully

         }).catch( (err) => {
           // An error occurred while clearing the collection.

         })
    

销毁集合将永久删除所有数据、所有存取器和安全工件。集合一旦销毁,将无法复原。将销毁应用程序的所有集合。

    	WLJSONStore.destroy()
    

补充阅读

有关 React Native 应用程序中 JSONStore 的详细信息,请参阅此处

参考

Inclusive terminology note: The Mobile First Platform team is making changes to support the IBM® initiative to replace racially biased and other discriminatory language in our code and content with more inclusive language. While IBM values the use of inclusive language, terms that are outside of IBM's direct influence are sometimes required for the sake of maintaining user understanding. As other industry leaders join IBM in embracing the use of inclusive language, IBM will continue to update the documentation to reflect those changes.
Last modified on June 01, 2020