1.7.27 • Published 3 years ago

react-native-easy-app v1.7.27

Weekly downloads
18
License
ISC
Repository
github
Last release
3 years ago

react-native-easy-app (React Native One-stop solution)

查看中文文档

Installation

npm install react-native-easy-app --save

or

yarn add react-native-easy-app

Features

  • Support for fast synchronous access to AsyncStorage
  • Support for flexible Http requests through optional configuration
  • Support for Flexible base widget (no sensory multi-screen adaptation)

Usage

For detailed usage, please refer to the example project Sample, Sample_MobX, Sample_Redux, Sample_Hook

You can also refer to the introduction of react-native-easy-app article : 简书

  • Implement a persistent data store manager ( based AsyncStorage )

       export const RNStorage = {// RNStorage : custom data store object
           token: null, // string type
           isShow: null, // bool type
           userInfo: null, // object type
       };
      import { XStorage } from 'react-native-easy-app';
      import { AsyncStorage } from 'react-native';
       
      XStorage.initStorage(RNStorage, AsyncStorage, () => {
          ... // RNStorage 【Property access code snippet】
      });
      
      // OR ---------------------------------------------------------------
      
      const result = await XStorage.initStorageSync(RNStorage, AsyncStorage);
      if (result) {
          ... // RNStorage 【Property access code snippet】
      }
              
     // RNStorage 【Property access code snippet】
     
     // From now on, you can write or read the variables in RNStorage synchronously
     
     console.log(RNStorage.isShow);
     // equal to [console.log(await AsyncStorage.getItem('isShow'))] 
      
     RNStorage.token = 'TOKEN1343DN23IDD3PJ2DBF3==';
     // equal to [ await AsyncStorage.setItem('token',TOKEN1343DN23IDD3PJ2DBF3==') ]  
     
     RNStorage.userInfo = {name: 'rufeng', age: 30};
     // equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ]  

    XStorage Object

    MethodparamReturnTypeDescription
    initStorage(storageObj, storageImp, initCallback, dataCallback?)voidEstablish the mapping relationship between storageObj and AsyncStorage
    initStorageSync(storageObj, storageImp, dataCallback?)PromiseEstablish the mapping relationship between storageObj and AsyncStorage
    multiGetkeys :string[]Promise<string, string>equal to AsyncStorage.multiGet()
    saveItemskeyValuePairs :stringPromiseequal to AsyncStorage.multiSet()
    removeItemskeys :string[]Promiseequal to AsyncStorage.multiRemove()
    clearnonevoidequal to AsyncStorage.clear()

    XStorage.initStorage parameters

    Parameter NamerequiredmodeDescription
    storageObj :objecttrue{ token:undefined, userName:undefined, ...}list of data that needs to be persisted
    storageImp :AsyncStoragetrueAsyncStoragedata Persistence Implementation Carrier
    initializedFunc :callback functiontrue()=>{ ... }callback after persistent mapping success
    dataChangedFunc ?:callback functionfalse(dataSet)=>{ ... }persistent data change callback

    Note: If the React Native version of the project is higher than 0.60, the parameters of storageImp, it is recommended to use the AsyncStorage instance in '@react-native-community/async-storage'

  • Configurable Http request framework

    • All based on configuration (configuration optional, free to set)

      import { XHttpConfig, XHttpConst } from 'react-native-easy-app';
      
      XHttpConfig().initLogOn(true)
                   .initBaseUrl('https://www.baidu.com')
                   .initTimeout(15000)
                   .initContentType(XHttpConst.CONTENT_TYPE_URLENCODED)
                   .initLoadingFunc((isLoading)=>{
                      ...
                   })
                   .initHeaderSetFunc((headers, request) => {
                      ...
                   })
                   .initParamSetFunc((params, request) => {
                      ...
                   })
                   .initParseDataFunc((result, request, callback) => {
                      let {success, json, response, message, status} = result;
                      ...
                    }
               );

      XHttpConfig Object (All method are optional)

      MethodparamReturnTypeDescription
      constructorserverTag ?:stringXHttpConfig BuilderCorresponding to the server serverTag of XHttp
      initBaseUrlbaseUrl :stringXHttpConfig Builderset baseUrl
      initTimeouttimeout :numberXHttpConfig Builderset common timeout
      initLogOnlogOn :boolXHttpConfig Builderset print request log or not
      initContentTypecontentType :stringXHttpConfig Builderset common contentType
      initLoadingFunc(isLoading) => {...}XHttpConfig Buildercallback http request loading status
      initHeaderSetFunc(headers, request) => {...}XHttpConfig BuilderIntercept header settings
      initParamSetFunc(params, request) => {...}HttpRequest BuilderIntercept params settings
      initParseDataFunc(result, request, callback) => {...}XHttpConfig BuilderIntercept interface returns data parsing
      initEncodeURIComponentencodeComponent :booleanHttpRequest BuilderSet common parameters(body) URL encoding,while contentType is application/x-www-form-urlencoded
      initNetworkExceptionFunc(NetInfo,(message, code) => {...})HttpRequest BuilderProvide the request library with a tool library to check the current network status (an instance object of @react-native-community/netinfo) require => android.permission.CHANGE_NETWORK_STATE
  • Send request template

       import { XHttp } from 'react-native-easy-app';
    
       let url = 'v1/account/login/';
       let param = { phone: '18600000000', authCode: '123456'};
       let header = { Authorization: "Basic Y3Rlcm1pbmF......HcVp0WGtI"};
       let callback = () => (success, json, message, status, respoonse) => {
            if (success) {
               showToast(JSON.stringify(json))
            } else {
               showToast(msg)
            }
       };
    
       * Settable parameters are spliced in builder form
       XHttp().url(url)
           .header(header)
           .param(param)
           .internal(true)
           .rawData()
           .pureText()
           .timeout(10000)
           .extra({tag: 'xx'})
           .contentType('text/xml')
           .loadingFunc((loading)=> showLoading('Please wait for a moment ...', loading))
           .rawData()
           .pureText()
           .configCommonFunc(true,true)
           .[formJson|formData|formEncoded]()
           .[get|post|put|patch|delete|options](callback);
      

    HttpRequest Object

    MethodparamsReturnTypeDescription
    constructorserverTag :stringHttpRequest BuilderCorresponding to the server serverTag of XHttpConfig
    urlurl :stringHttpRequest Builderset full url or url suffixes
    header{ Accept, Authorization ... } :objectHttpRequest BuilderSet the headers parameters
    param{ userName,... } or FormData :objectHttpRequest BuilderSet the body parameters
    paramRaw{ userName,... } or FormData :objectHttpRequest BuilderSet the body parameters (paramRaw will be passed directly to the body of fetch)
    contentTypecontentType :stringHttpRequest Builderset current request contentType (common contentType Settings will be replaced)
    internalinternal :boolHttpRequest Builderset request tag (default true), And then you can get it anywhere there's a request
    extra{customTag ...}HttpRequest Builderset request custom tag And then you can get it anywhere there's a request
    timeouttimeout :numberHttpRequest Builderset current request timeout (common timeout Settings will be replaced)
    loadingFunc(isLoading)=>{ ... }HttpRequest Builderrequest status callback (Reflects the status is loading or not)
    configCommonFunc( enableHeaderFunc :bool, enableParamFunc :bool )HttpRequest Builderset common config initHeaderSetFunc are valid or not
    rawDatanoneHttpRequest BuilderSets the callback result to return raw json (initParseDataFunc will be ignored)
    pureTextnoneHttpRequest BuilderSet the callback result to return plain text
    formJsonnoneHttpRequest Builderequal to set ( headers'Content-Type' = 'application/json' )
    formDatanoneHttpRequest Builderequal to set ( headers'Content-Type' = 'multipart/form-data' )
    formEncodednoneHttpRequest Builderequal to set ( headers'Content-Type' = 'application/x-www-form-urlencoded' )
    get(success, json, message, status ,response) => voidvoidget request callback
    post(success, json, message, status ,response) => voidvoidpost request callback
    options(success, json, message, status ,response) => voidvoidoptions request callback
    put(success, json, message, status ,response) => voidvoidput request callback
    delete(success, json, message, status ,response) => voidvoiddelete request callback
    patch(success, json, message, status ,response) => voidvoidpatch request callback
    request(method, (success, json, message, status ,response) => void )voidrequest callback for specified method
    executemethod :stringPromiserequest for the specified method returned in the form of a promise
    fetchmethod :stringPromisereturns a fetch result without any processing

    new HttpRequest() ==> XHttp()

    It is recommended that it be more convenient to send requests using XHttp()

  • request-send

    • synchronous request
         import { XHttp } from 'react-native-easy-app';
         
         const url = 'https://www.google.com';
        
         const result = await XHttp().url(url).execute('GET');
         const {success, json, message, status, response} = result;
         
         if(success){
            this.setState({content: JSON.stringify(json)})
         } else {
            showToast(message)
         }
    • asynchronous request mode 1
         XHttp().url(url).get((success, json, message, status, response)=>{
             if (success){
                this.setState({content: JSON.stringify(json)});
             } else {
                showToast(msg);
             }
         });
             
    • asynchronous request mode 2
         XHttp().url(url).execute('GET').then(({success, json, message, status, response}) => {
             if (success) {
                  this.setState({content: JSON.stringify(json)});
             } else {
                  showToast(message);
             }
          })
  • Flexible base widget

       XView
       XImage
       XText
       
       XFlatList
       
       XWidget
       .initResource(AssetsBaseUrl)    // The uri prefix of the icon attribute of the XImage component
       .initReferenceScreen(375, 677); // The component scales the reference screen size

    XView, XImage, and XText all contain the raw attribute. If the raw value is true, the setting of XWidget.initReferenceScreen (referenceWidth, referenceHeight) is ignored: multi-screen size adaptation is not automatically processed

    XView Object

    PropertytypeDescription
    rawbooldefault:false, if true, the multi-screen adaptation function will be disabled.
    ......If the onPress or onLongPress property is included, it has the same property as TouchableXXX, otherwise it has the same property as View

    XImage Object

    PropertytypeDescription
    rawbooldefault:false, If true, the multi-screen adaptation function will be disabled.
    iconstringequivalent to Image's srouce attribute,Can accept such as https://xxx.yy.com/../image.jpg, data: image / png; base64, iVBORw0KGgoAAAAN ... or require ('./ image.jpg')
    iconSizenumberthe size of the image has priority over the width and height of the style
    ......if the onPress and onLongPress functions are set, XImage will be wrapped by XView, and the externally passed properties will be automatically assigned to the correct control

    XText Object

    PropertytypeDescription
    rawbooldefault:false, If true, the multi-screen adaptation function will be disabled.
    textstringtext
    textExtendboolif the icon is included, it is equivalent to setting the property of the Text component: {flex: 1}
    iconstringequivalent to Image's srouce attribute,Can accept such as https://xxx.yy.com/../image.jpg, data: image / png; base64, iVBORw0KGgoAAAAN ... or require ('./ image.jpg')
    resizeModestringicon resizeMode
    iconSizenumbericon size
    iconStyleobjecticon style
    iconMarginnumberdistance between icon and text
    iconPositionstringthe position of the icon in the View, only the following values can be set: 'top', 'right', 'bottom', 'left'
    ......if the onPress and onLongPress functions are set, XText will be wrapped by XView, and the externally passed properties will be automatically assigned to the correct control

    XFlatList Object

    PropertytypeDescription
    dataarrayequivalent to data of FlatList control
    refreshStatusobjectXFlatList list displays UI styles and text setting objects in different refresh states
    indicatorPropsobjectset the style and attributes of RefreshControl
    onRefresh() => {...}equivalent to onRefresh of FlatList control
    onLoadMore() => {...}When the list scrolls to the bottom, the callback method is executed (when more data needs to be loaded)
    renderEmptyViewFunc(status, isEmpty) => {...}Customize the realization of EmptyView in various states
    renderRooterViewFunc(status, isEmpty) => {...}Customize the implementation of RooterView in various states
    ......all remaining properties of FlatList component

    FlatList component refreshStatus attribute example

     const RefreshStatus = {
       Idle: {}, //idle status
     
       RefreshingData: {  text: 'Loading...' }, // Pull-down refresh..
       NoData: {  text: 'No data' }, // To drop down to refresh (no data).
       LoadFailure: {  text: 'Failed to load' }, // Drop-down refresh (load failed)
     
       LoadingMoreData: { moreText: 'Loading more data…' }, // Load more, in progress...
       NoMoreData: { moreText: 'No more data' }, // Load more (no data)
       LoadMoreFailure: { moreText: 'Click to reload' }, // Load more (load failed)
       
       NetException: {text: 'network exception', moreText: 'Network exception, click reload'}, // network exception
     }

    For detailed usage, please refer to the example project Sample, Sample_MobX, Sample_Redux, Sample_Hook

    You can also refer to the introduction of react-native-easy-app article : 简书

Version log

  • 1.7.0 XStorage initialization adds required parameter storageImp (AsyncStorage instance)
  • 1.7.4 Set the default timeout of XHttpConfig to 15 seconds; update the readme file and add XStorage synchronization initialization code snippets.
  • 1.7.5 Remove the parameter urlEncoded processing of specific request, only support global encoding or no encoding; fix the encoding processing under non-formEncoded type.
  • 1.7.6 Set the default contentType of XHttpConfig to application/x-www-form-urlencoded; set the default icon of XText to be at the top of the text.
  • 1.7.7 XText adds iconStyle and resizeMode attributes; XHttp common parameters add support for incoming FormData, the original parameter paramRaw supports sending the request directly without processing.
  • 1.7.8 Fix the bug that XImage does not support tintColor style when there is a click event.
  • 1.7.9 XFlatList adds ref attribute: ref => this.flatList = ref, so that XFlatList can support the related methods owned by FlatList, the usage is as follows: this.refreshList.flatList.scrollToOffset({...}).
  • 1.7.12 When the request is successful, the meaningless timeout timer is cleared in time to reduce unnecessary waste of timer resources.
  • 1.7.13 XFlatList adds attributes renderFooter, indicatorProps to control its style and attributes more flexibly.
  • 1.7.16 XFlatList adds attributes such as indicatorProps, renderEmptyViewFunc, renderRooterViewFunc, etc., which can customize the layout of indicator, emptyView in various states and rooterView
  • 1.7.17 XFlatList adds attribute renderPreEmptyViewFunc, which is used to customize the layout of EmptyView when the list is not loaded with any data.
  • 1.7.18 HttpConfig adds the initNetworkExceptionFunc method, through the @react-native-community/netinfo instance object specified by the user, the corresponding callback processing is done according to the current network status when requesting
  • 1.7.19 XFlatList merges renderPreEmptyViewFunc into renderEmptyViewFunc method, removes XText’s default support for allowFontScaling
  • 1.7.20 Fix the bug that the judgment condition of the screen adaptation method validReferSize is wrong
  • 1.7.23 Removed unnecessary data type conversion implementation when XStorage reads data from persistence to memory
  • 1.7.25 Compatible XStorage data storage can not effectively handle the bug of undefined type data (an exception will be reported on IOS)
  • 1.7.26 Rename the XHttpConfig method initHttpLogOn to initLogOn, rename the XFlatList method renderRooterViewFunc to renderFooterViewFunc, modify the readme document description
1.7.27

3 years ago

1.7.26

3 years ago

1.7.24

3 years ago

1.7.25

3 years ago

1.7.23

3 years ago

1.7.21

3 years ago

1.7.22

3 years ago

1.7.20

3 years ago

1.7.19

4 years ago

1.7.18

4 years ago

1.7.17

4 years ago

1.7.16

4 years ago

1.7.15

4 years ago

1.7.14

4 years ago

1.7.13

4 years ago

1.7.11

4 years ago

1.7.12

4 years ago

1.7.10

4 years ago

1.7.9

4 years ago

1.7.8

4 years ago

1.7.7

4 years ago

1.7.6

4 years ago

1.7.5

4 years ago

1.7.4

4 years ago

1.7.3

4 years ago

1.7.2

4 years ago

1.7.1

4 years ago

1.7.0

4 years ago

1.6.12

4 years ago

1.6.11

4 years ago

1.6.10

4 years ago

1.6.9

4 years ago

1.6.8

4 years ago

1.6.7

4 years ago

1.6.6

4 years ago

1.6.5

4 years ago

1.6.4

4 years ago

1.6.3

4 years ago

1.6.2

4 years ago

1.6.1

4 years ago

1.6.0

4 years ago