首页 > 解决方案 > 如何在从关闭更改为打开时检查 wifi 状态

问题描述

我想使用本机模块在 react-native 中使用服务,如果 Wifi 连接从关闭更改为打开,只需显示连接更改的 toast

标签: react-nativereact-native-androidnative-modulereact-native-native-module

解决方案


您可以使用react-native-netinfo插件。安装此插件,然后将以下代码添加到您的文件中:

import NetInfo from '@react-native-community/netinfo';
...
...

class App extends Component {
    netInfoHandler;
    constructor(props) {
        super(props);
        this.state = {
            isConnected: true
        }
    }

    componentDidMount = () => {
        this.netInfoHandler = NetInfo.addEventListener(async (state) => {
            if (this.state.isConnected !== state.isConnected) {
                this.setState({ isConnected: state.isConnected });
                // show toast here
            }
        });
    }

    componentWillUnmount = () => {
        this.netInfoHandler();
    }

    render() {
        return (
            ...
            // your view
        )
    }
}

export default App

推荐阅读