这篇文章主要介绍了关于如何利用js fetch实现ping效果,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下
实际业务终于到的,在部分环境中可能存在网络不稳定的因素,wms手持有时候联网了但实际访问不到网页,很是尴尬
网上找到的大多数方案是通过image去实现的,我也曾参照过,但似乎效果不好
于是利用fetch写了个
import React, { Component } from 'react'
import { View,TextInput,ScrollView,Text } from 'react-native'
import { List, Button,Flex } from 'antd-mobile'
const Item = List.Item
class PingTest extends Component {
constructor(props) {
super(props)
// 初始状态
this.state = {
ping:'',
msglist:[],
}
this.cycle = null
}
pingCycle = () => {
const { ping,msglist } = this.state
const start = (new Date()).getTime()
fetch(`http://${ping}`).then(() => {
const delta = (new Date()).getTime() - start
if (delta > 5000) {
msglist.push({
status: 0,
msg: `ping ${ping} 连接超时`,
})
} else {
msglist.push({
status: 1,
msg: `ping ${ping} time=${delta} ms`,
})
}
this.setState({
msglist,
})
}).catch((err) => {
msglist.push({
status: 0,
msg: `ping ${ping} 连接失败`,
})
this.setState({
msglist,
})
})
}
handlePing = () => {
this.cycle = setInterval(this.pingCycle,1000)
}
handleStopPing = () => {
clearInterval(this.cycle)
}
render() {
const {msglist} = this.state
return (
<View style={{ height: '100%'}}>
<List>
<Item>
<TextInput
onChangeText={text => this.setState({ping: text})}
/>
</Item>
<Item>
<Flex>
<Flex.Item flex={1}><Button type="primary" onClick={this.handlePing.bind(this)}>Ping</Button></Flex.Item>
<Flex.Item flex={1}><Button onClick={this.handleStopPing.bind(this)}>停止</Button></Flex.Item>
</Flex>
</Item>
</List>
<ScrollView style={{ height: 200,backgroundColor:"#000"}}>
{msglist.length ? msglist.map(e =>
<Flex>
<Flex.Item>
<Text style={{color: e.status === 1 ? '#87d068' : '#f50'}}>{e.msg}</Text>
</Flex.Item>
</Flex>):null}
</ScrollView>
</View>
)
}
}
export default PingTest![1531296201402381.png 3437791867-5b45906ca23ca_articlex[1].png](https://img.php.cn//upload/image/783/153/250/1531296201402381.png)
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
以上就是如何利用js fetch实现ping效果的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号