gpt4 book ai didi

javascript - 如何监控 react 组件中的网络状态变化

转载 作者:行者123 更新时间:2023-11-30 10:58:31 25 4
gpt4 key购买 nike

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

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

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

最佳答案

类组件的简化示例:

// 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
}
}

关于javascript - 如何监控 react 组件中的网络状态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59033829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com