跳到主要内容

useNetworkType

警告

由于获取网络信息为异步, 故初始值为unknown. 该 hook 会自动监听当前环境 networkType

useNetworkType

获取网络类型

何时使用

当需要根据当前网络类型做判断时

API

const networkType: keyof NetworkType = useNetworkType(autoListen?: boolean);

参数说明

参数说明类型默认值
autoListen是否自动开始监听booleantrue

返回值说明

返回值说明类型
networkType当前网络类型keyof NetworkType

NetworkType

类型
wifiwifi
2g2g
3g3g
4g4g
5g5g
unknownunknown
nonenone

代码演示

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>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️✔️✔️