React native 当网络在线/离线更改时,NetInfo.addEventListener正在多次调用
它应该只打一次电话。当NetInfo.addEventListener调用它时,调用三次。我想叫它一次React native 当网络在线/离线更改时,NetInfo.addEventListener正在多次调用,react-native,React Native,它应该只打一次电话。当NetInfo.addEventListener调用它时,调用三次。我想叫它一次 NetInfo.fetch().then(state => { props.connectionState(state.isConnected) NetInfo.addEventListener('connectionChange', state => { props.connectionState(state.isCo
NetInfo.fetch().then(state => {
props.connectionState(state.isConnected)
NetInfo.addEventListener('connectionChange', state => {
props.connectionState(state.isConnected)
AsyncStorage.getItem('responseData').then(data => {
if (data !== null) {
let response = JSON.parse(data)
console.log('length', response.length)
response.forEach(element => {
props.submitDataOffline(element)
});
}
});
});
});
您需要取消订阅每个已订阅的侦听器。否则,它们将在加载视图时累积
// component methods to register networkInfo
componentDidMount() {
this.unsubscribe = NetInfo.addEventListener(this.connectionChange);
}
// component methods to unregister networkInfo and appState listener
componentWillUnmount() {
this.unsubscribe();
}
因此,我将重写您的代码,如下所示:
constructor(props) {
NetInfo.fetch().then(state => props.connectionState(state.isConnected)});
this.unsubscribe = NetInfo.addEventListener('connectionChange', state => {
props.connectionState(state.isConnected)
AsyncStorage.getItem('responseData').then(data => {
if (data !== null) {
let response = JSON.parse(data)
console.log('length', response.length)
response.forEach(element => {
props.submitDataOffline(element)
});
}
});
});
});
}
componentWillUnmount() {
this.unsubscribe();
}
您的问题是什么?NetInfo.addEventListener应该只调用一次。您应该只调用.addEventListener一次,但这段代码显然位于组件内部,并且每次运行此代码时都会不断添加新的侦听器