useNetworkType
警告
由于获取网络信息为异步, 故初始值为unknown. 该 hook 会自动监听当前环境 networkType
useNetworkType
获取网络类型
何时使用
当需要根据当前网络类型做判断时
API
const networkType: keyof NetworkType = useNetworkType(autoListen?: boolean);
参数说明
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
autoListen | 是否自动开始监听 | boolean | true |
返回值说明
返回值 | 说明 | 类型 |
---|---|---|
networkType | 当前网络类型 | keyof NetworkType |
NetworkType
类型 | 值 |
---|---|
wifi | wifi |
2g | 2g |
3g | 3g |
4g | 4g |
5g | 5g |
unknown | unknown |
none | none |
代码演示
- React
- Vue
network/useNetworkType/index
import React from 'react';
import DemoContent from '@src/components/DemoContent';
import { Radio, Cell } from '@taroify/core';
import { showToast } from '@tarojs/taro';
import { useEffect } from '@taro-hooks/core';
import { escapeState } from '@taro-hooks/shared';
import { useNetworkType } from 'taro-hooks';
// @ts-ignore
import { NETWORKTYPE } from '@root/public/constant';
export default () => {
const networkType = useNetworkType();
useEffect(() => {
showToast({
title: '当前网络类型为: ${escapeState(networkType)}',
icon: 'none',
mask: true,
});
}, [networkType]);
return (
<DemoContent>
<Radio.Group value={escapeState(networkType)}>
<Cell.Group clickable>
{Object.entries(NETWORKTYPE).map(([key, value]) => (
<Cell key={key} title={'网络类型: ' + value}>
<Radio
disabled={value !== escapeState(networkType)}
name={value}
/>
</Cell>
))}
</Cell.Group>
</Radio.Group>
</DemoContent>
);
};
network/useNetworkType/index
<template>
<demo-content>
<nut-radiogroup v-model="networkType">
<nut-radio
v-for="(value, key) in NETWORKTYPE"
:key="key"
:disabled="value !== networkType"
:label="value"
shape="button"
>网络类型: {{ value }}</nut-radio
>
</nut-radiogroup>
</demo-content>
</template>
<script setup lang="ts">
import { showToast } from '@tarojs/taro';
import { useEffect } from '@taro-hooks/core';
import { useNetworkType } from 'taro-hooks';
import { escapeState } from '@taro-hooks/shared';
// @ts-ignore
import { NETWORKTYPE } from '@root/public/constant';
const networkType = useNetworkType();
useEffect(() => {
showToast({
title: '当前网络类型为: ${escapeState(networkType)}',
icon: 'none',
mask: true,
});
}, [networkType]);
</script>
Hook 支持度
微信小程序 | H5 | ReactNative |
---|---|---|
✔️ | ✔️ | ✔️ |