javascript - react组件中如何监控网络状态变化
问题描述
有两个事件监听器在监视网络状态时显然很有用:
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
}
}
推荐阅读
- sql - 营销流程的工作流程
- jmeter - JMeter - JSON 响应操作在带有 java 的 JSR223 处理器中不起作用
- php - 使用 Laravel Eloquent 进行子查询以检索属性的答案
- python - 如何从熊猫数据框中的多列创建单个饼图
- sql - SQL减去同一列但不同行中的时间戳
- c# - Graph API 日历视图事件分页
- mysql - 本地/服务器上相同数据库的不同 sql 查询结果
- php - WordPress wp_remote_retrieve_body() 返回空但邮递员返回值
- python - pyspark sql 为展开的行添加不同的 Qtr start_date、End_date
- python - 当在 shell 脚本中调用 python 脚本时,将变量从 python 脚本传递到 shell 脚本