在React Native程序中处理离线/在线连接的便利工具

网友投稿 848 2022-10-27

在React Native程序中处理离线/在线连接的便利工具

在React Native程序中处理离线/在线连接的便利工具

react-native-offline

Handful of utilities you should keep in your toolbelt to handle offline/online connectivity in React Native. It supports iOS, Android and Windows platforms. You can leverage all the functionalities provided or just the ones that suits your needs, the modules are conveniently decoupled.

Example app

A comprehensive example app is available within Expo to play with the library and better understand its different modules. Go and check it out!

Contents

MotivationFeaturesContributionsSponsorsInstallationAPIComponent UtilitiesNetworkProviderNetworkConsumer Integration with ReduxNetwork reducerReduxNetworkProvidernetworkSagacreateNetworkMiddlewareOffline Queue Other UtilitiescheckInternetConnection MiscellaneaFAQTesting offline behaviourDispatching CONNECTION_CHANGE as 1st action on app startupIntercept and queue actions based off server errorsPersist and rehydrate thunks in the offline queueUsing redux-saga 1.0.0-beta.x InspirationLicenseContributors

Motivation

When you are building your React Native app, you have to expect that some users may use your application in offline mode, for instance when travelling on a Plane (airplane mode) or the underground (no signal). How does your app behave in that situation? Does it show an infinite loader? Can the user still use it seamlessly?

Having an offline first class citizen app is very important for a successful user experience. React Native ships with the NetInfo module in order to detect internet connectivity. The API is pretty basic and it may be sufficient for small apps but its usage gets cumbersome as your app grows. Besides that, it only detects network connectivity and does not guarantee internet access so it can provide false positives.

This library aims to gather a variety of modules that follow React and Redux best practises, in order to make your life easier when it comes to deal with internet connectivity in your React Native application.

Features

Offline/online conditional rendering through Provider/Consumer components that leverage the new React Context APIReducer to keep your connectivity state in the Redux storeRedux middleware to intercept internet request actions in offline mode and apply DRY principleCompatibility with async middleware libraries like redux-thunk, redux-saga and redux-observableA saga to place the network event subscriptions outside of your componentsA step further than NetInfo detecting internet access besides network connectivityOffline queue support to automatically re-dispatch actions when connection is back online or dismiss actions based on other actions dispatched (i.e navigation related)Ability to check connectivity regularly100% unit test coverage

Contributions

PRs are more than welcome. If you're planning to contribute please make sure to read the contributing guide: CONTRIBUTING.md

Sponsors

If you use this library on your commercial/personal projects, you can help us by funding the work on specific issues that you choose by using IssueHunt.io!

This gives you the power to prioritize our work and support the project contributors. Moreover it'll guarantee the project will be updated and maintained in the long run.

Sponsors will be listed in the contributors section at the bottom. If you want to be removed please contact me at: rauliyohmc@gmail.com

Installation

RN >= 0.60

This library uses @react-native-community/netinfo behind the scenes, which contains native code, so you need to install it and link it as well. Follow the next steps in order:

$ yarn add react-native-offline$ yarn add @react-native-community/netinfo# extra step for iOS $ (cd ios && pod install)# Or if you use npm$ npm i react-native-offline$ npm i @react-native-community/netinfo# extra step for iOS$ (cd ios && pod install)

On RN 0.60, for Android, you may need to use jetifier to convert the native dependency to AndroidX.

Android

To request network info in Android an extra step is required, so you should add the following line to your app's AndroidManifest.xml as well:

Expo >= 35

If you are using the managed workflow, you don't need to install any extra dependency. Expo SDK already ships in with NetInfo.

$ yarn add react-native-offline# Or if you use npm$ npm i react-native-offline

API

Component Utilities

In order to render stuff conditionally with ease. They internally listen to connection changes and also provide an extra layer of reliability by ensuring there is internet access when reporting online. For that, an extra request is made to a remote server.

NetworkProvider

Provider component that injects the network state to children components via React Context. Only children prop is required, the rest are optional. It should be used on top of your components hierarchy, ideally in (or close to) the entry point.

type Props = { children: React.Node, pingTimeout?: number = 10000, pingServerUrl?: string = 'https://google.com/', shouldPing?: boolean = true, pingInterval?: number = 0, pingOnlyIfOffline?: boolean = false, pingInBackground?: boolean = false, httpMethod?: HTTPMethod = 'HEAD', customHeaders?: HTTPHeaders = {},}

Config

children: a React Element. This is the only required prop.

pingTimeout: amount of time (in ms) that the component should wait for the ping response. Defaults to 10000 ms. If you want to use a different value, it's recommended to use a higher one.

pingServerUrl: remote server to ping to. Defaults to https://google.com/ since it's probably one the most stable servers out there, but you can provide your own if needed. Warning: google.com is a blocked domain in China, so if you need your app to be accessible from there, you MUST use another domain.

shouldPing: flag that denotes whether the extra ping check will be performed or not. Defaults to true.

pingInterval: the interval (in ms) you want to ping the server at. Defaults to 0, and that means it is not going to check connectivity regularly. If opted in, it's advised not to choose a very small value, because that may drain your battery. Choose wisely. Something around 30000 ms should be fine.

pingOnlyIfOffline: when set to true and pingInterval > 0, it will ping the remote server regularly only if offline. Defaults to false.

pingInBackground: whether or not to check connectivity when app isn't in the foreground. Defaults to false.

httpMethod: http method used to ping the server. Supports HEAD or OPTIONS. Defaults to HEAD.

customHeaders: optional custom headers to add for ping request.

Usage

// index.jsimport React from 'react';import { NetworkProvider } from 'react-native-offline';import App from './App';const Root = () => ( );export default Root;

NetworkConsumer

React component that subscribes to connectivity changes. It requires a function as a child. The function receives the current connectivity status and returns a React node. This component should be rendered within a NetworkProvider in order to work properly.

Props

type NetworkState = { isConnected: boolean,}type Props = { children: ({ isConnected }: NetworkState) => React.Node}

Usage

import React from 'react';import { Image, Button, Text } from 'react-native';import { NetworkConsumer } from 'react-native-offline';const ImageViewer = () => ( {({ isConnected }) => ( isConnected ? (

上一篇:解决Spring在Thread中注入Bean无效的问题
下一篇:win10环境下 运行debug程序
相关文章

 发表评论

暂时没有评论,来抢沙发吧~