首页 > 解决方案 > react组件中如何监控网络状态变化

问题描述

有两个事件监听器在监视网络状态时显然很有用:

1. window.addEventListener('online', console.log('Online'));
2. window.addEventListener('offline', console.log('Offline'));

但我不确定在哪里注册和使用它们。当我在 中使用它们时componentDidMount,没有用,因为只有在安装组件时才会进行监视。我想在一个地方监视网络状态并在整个应用程序中使用它。为此,在 redux 中调度网络状态会更有帮助。但问题是在哪里监听这些事件。

标签: javascriptreactjsredux

解决方案


类组件的简化示例:

// In your main App component
componentDidMount() {
    window.addEventListener('online', () => this.props.setConnectivity('online'));
    window.addEventListener('offline', () => this.props.setConnectivity('offline'));

    // You don't need to worry about removeEventlistener if your main App component never unmounts.
}

// Action
const setConnectivity = (status) => ({
    type: 'SET_CONNECTIVITY',
    payload: status === 'online'
})

// Reducer
const connectivityReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'SET_CONNECTIVITY':
            return {
                ...state,
                isOnline: action.payload
            };
    }
};

// To let a component know about the connectivity status, simply use the flag from state:
const mapStateToProps = (state) => ({
    isOnline: state.connectivity.isOnline
});

// To react to status changes in any other component:
componentDidUpdate(prevProps) {
    const { isOnline } = this.props;

    if (!prevProps.isOnline && isOnline) {
        // We went online
    } else if (prevProp.isOnline && !isOnline) {
        // We went offline
    }
}

推荐阅读