React Native Tutorial-Invoke Web API

Source: Internet
Author: User



React-native's official website Fetch introduction: https://facebook.github.io/react-native/docs/network.html#content



React-native does not support $, that is, we cannot use $http to invoke the API, according to the React-native official website tutorial, we can use fetch, which is also a better network API, it can be used by default in react native.



In the React-native project, we still use our customary method, write a service JS to put all our API, but in React-native, we will have some definitions and use of methods of change.


Understanding Fetch


Fetch (input, init)



The first parameter, input, can be a string that contains the URL to get the resource;



The second parameter object is optional, and it can customize some parts of the HTTP request;



method: The method used by the request, such asGET、POST。



headers: The header information of the request, in the form of anHeadersobject orByteString.



body: Requested body information: may be aBlob,,BufferSourceFormData,,URLSearchParamsorUSVStringobject. Note that the GET or HEAD method request cannot contain body information.



mode: The requested mode, such ascors、no-cors 或者same-origin。



credentials: The requested credentials, asomit、same-origin 或者include。



cache: Requested cache mode:,,,,defaultno-storereloadno-cacheforce-cache, oronly-if-cached.



The return value of Fectch () is a promise object that can usethenandcatchspecify a callback function:


fetch(input, init)
.then((response) => response.json())
        .then((responseJson) => {console.log(responseText);})
        .catch((error) => {console.warn(error);});
FETCH returns the parameter definition of the function callback ():Fetch return function parameter definition
    1. If the interface call succeeds, we return callback (Null,data); there are two parameters:
      The first parameter is NULL, which represents the success of the interface invocation;
      The second parameter is data for the interface returned;
    2. If the interface is not successful, we return callback (ERR); only one parameter: Err is the error message;
Fetch Example


When you use this method, you do not need to bring in fetch, just use it.



Let's start by outlining what the service API features of the feedback demo are:


    1. Get information about the app based on the app's GUID (Get method);
    2. The user sends the completed content (POST method)


The interface implementation of the app is not rendered, the main explanation is how to invoke the Web API.



First to build a service: App-feedback-svc.js. The code is as follows:


var baseURL = "http://192.168.89.101:8082/api/",
 
export default {
// Get detailed information of an app (excluding comments)
    getOneAppInfoDetail (appGUID, callback) {
        fetch (baseURL + ‘api / app / app-info /’ + appGUID, {
            method: ‘GET’
        }). then ((response) => response.json ())
            .then ((responseJson) => {
                switch (responseJson.State) {
                    case 0:
                        var listOption = responseJson.Result.ListOption;
                        var result = {
                            tags: listOption.filter ((item) => item.OptionClass === 0) .map ((item) => item.OptionString),
                            expect: listOption.filter ((item) => item.OptionClass === 1) .map ((item) => item.OptionString)
                        };

                        callback (null, result);
                        break;
                    case 1:
                        callback ('Invalid parameter');
                        break;
                    case 2:
                        callback (‘Unknown error (exception)’);
                        break;
                    default:
                        callback ('Other errors');
                        break;
                }
            })
            .catch ((error) => {
                callback (error);
            });
    },

    // Save app reviews
    saveAppComment (AppGUID, IsLike, CommentDetail, WishFeature, PhoneType, Email, callback) {
        var wishItem = ();
        WishFeature.filter ((item) => item.check == true) .map ((item, index) => (
            wishItem [‘Item’ + index] = item.label
        ));
        fetch (baseURL + ‘api / comment / save-comment’, {
            method: ‘POST’,
            headers: {
                ‘Accept’: ‘application / json’,
                ‘Content-Type’: ‘application / json’
            },
            body: JSON.stringify ({
                AppGUID: AppGUID,
                IsLike: IsLike,
                CommentDetail: CommentDetail,
                WishFeature: wishItem,
                PhoneType: PhoneType,
                Email: Email
            })
        }). then ((response) => response.json ())
            .then ((responseJson) => {
                switch (responseJson.State) {
                    case 0:
                        callback (null);
                        break;
                    case 1:
                        callback ('Invalid parameter');
                        break;
                    case 2:
                        callback (‘Unknown error (Exception)’);
                        break;
                    default:
                        callback ('Other errors');
                        break;
                }
            })
            .catch ((error) => {
                callback (error);
            });
    }
}


Service JS assume the role of transfer, so we need to deal with the format of the data returned by the interface, as far as possible after the conversion of the service JS, and then used in the page.



For example, in the above file, get the app information function Getoneappinfodetail (), the data returned by the interface has all the app information, but we do not need so much information on the page, so we need in the service, when the interface call is successful and the data is returned, We want to reconstruct the data format we need:


//responseJson.State==0
  var listOption = responseJson.Result.ListOption;
  var result = {
      tags: listOption.filter ((item) => item.OptionClass === 0) .map ((item) => item.OptionString),
      expect: listOption.filter ((item) => item.OptionClass === 1) .map ((item) => item.OptionString)
  };
  callback (null, result);
 
// The returned data result contains only the data we need.


when the page invokes the API, the parameters in the defined service function are passed to get information about the app or to save the user's feedback.



Get app Info:



Using the Fetch method, we only need one parameter (appGUID) to get the app's information.



According to the data of the return function callback () in the service, we judge whether the first parameter is empty to determine whether our interface is successful or not, and whether we can get the data we want.


import feedbackSvc from ‘./services/app-feedback.js’;
 
componentDidMount () {
     feedbackSvc.getOneAppInfoDetail (this.appGUID, function (info, data) {
         if (info == null) {
             var appDetailInfo = data;
             var list = appDetailInfo.expect.map ((item) => ((check: false, label: item)));
             list.push ({check: false, label: "Other features"});
             this.setState ((appDetailInfo, list));
         } else {
             alert (info);
         }
     } .bind (this));
}


To Save the feedback content:



Using the Fetch POST method, we need to pass each content of the feedback as a parameter to the interface, and the format of these parameters to be consistent with the parameters required by the interface to successfully save the content, of course, like the Get method, the interface returned by the data format is not necessarily what we want, similarly, The data format obtained by our foreground page is not necessarily the format required by the interface, and the code for converting the data format should also be processed in the service JS. As Saveappcomment () in App-feedback-svc.js, the wishfeature in our page is an array, but the interface needs an object, so we need to format it:


var wishItem = ();
  WishFeature.filter ((item) => item.check == true) .map ((item, index) => (
      wishItem [‘Item’ + index] = item.label
  ));
 
// In this way, the wishItem object we get is the data required by the interface


page, when the user clicks the "Send" button, the user fill in the data is uploaded to the interface to save, so we need to define a function _savecomment (), when the user clicks on the function called, all content as parameters to the interface, if the calling interface succeeds, Users fill in the data will be saved in our management background.


import feedbackSvc from ‘./services/app-feedback.js‘;

 
_saveComment() {
    feedbackSvc.saveAppComment(this.appGUID, this.state.isLike, this.state.appOption, this.state.list, phoneType, this.state.email, function (info, data) {
        if (info == null) {
            alert(‘Thanks for your feedback!‘);
        } else {
            alert(info);
        }
    }.bind(this))
}


React Native Tutorial-Invoke Web API


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.