React Network 当网络掉线和重连在线时通知您的应用程序

网友投稿 644 2022-10-30

React Network 当网络掉线和重连在线时通知您的应用程序

React Network

What?

Notifies your app when the network connection goes online or offline.

Why?

Because the next billion users of the internet will have a decent device but a spotty connection. Having a component to help you declaratively deal with that is super fantastic.

Installation

npm install react-network# oryarn add react-network

And then import it:

// using es modulesimport Network from 'react-network'// common.jsconst Network = require('react-network').default// AMD// I've forgotten but it should work.

Or use script tags and globals.

And then grab it off the global like so:

const Network = ReactNetwork.default

How?

// import Network from 'react-network'const Network = ReactNetwork.defaultReactDOM.render(( { if (online && window.cornify_add) { window.cornify_add() } }} render={({ online }) =>

Every time you go back online, a unicorn is born!

You can open up the devtools to simulate losing the network, or actually turn off your wifi to see these demos.

{online ? "You are online." : "You are at a hotel." }

} />), DOM_NODE)

Props

render

Whatever you'd like to render in response to changes in the network.

// import Network from 'react-network'const Network = ReactNetwork.defaultReactDOM.render((

You are online: {online ? 'Yep' : 'Nope'}.

}/>), DOM_NODE)

onChange

Called whenever the network goes on or offline. This is useful to fire off some imperative code, like adding unicorns to the page or more practically, avoiding resource fetching until the network comes back online.

// import Network from 'react-network'const Network = ReactNetwork.defaultclass App extends React.Component { state = { image: null } handleNetworkChange = ({ online }) => { if (online) { this.fetch() } else { clearTimeout(this.timeout) } } fetch = () => { fetch('https://unsplash.it/640/400/?random') .then(res => res.blob()) .then(blob => { var image = URL.createObjectURL(blob) this.setState({ image }) this.timeout = setTimeout(this.fetch, 5000) }) } render() { return (

{this.state.image ? ( ) : (

Loading first image

)} ( online ? null : (

You are offline, images will continue when you get back online.

) )} />
) }}ReactDOM.render(, DOM_NODE)

Legal

Released under MIT license.

Copyright © 2017-present React Training LLC

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:DSS中自定义原子操作atomic
下一篇:MFC对话框中绘制橡皮筋矩形
相关文章

 发表评论

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