我正在使用RN NetInfo来检查用户是否使用组件<NetworkProvider />
连接到了Internet,并且希望将此组件stats
传递到应用程序中的所有屏幕和组件。
问题在于,当我在render
函数中使用上下文api时,上下文api可以很好地工作,但是在componentDidMount
或componentWillMount
中使用时,状态api不会改变。返回isConnected
状态的初始值。
请阅读代码注释
这就是我的代码
NetworkProvider.js
import React,{PureComponent} from 'react';
import NetInfo from '@react-native-community/netinfo';
export const NetworkContext = React.createContext({ isConnected: true });
export class NetworkProvider extends React.PureComponent {
state = {
isConnected: true // initial value
};
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
}
handleConnectivityChange = isConnected => this.setState({ isConnected });
render() {
return (
<NetworkContext.Provider value={this.state}>
{this.props.children}
</NetworkContext.Provider>
);
}
}
此index.js
...
import { NetworkContext } from '../components/NetworkProvider';
export default class index extends Component {
static navigationOptions = {};
static contextType = NetworkContext;
constructor(props) {
super(props);
this.state = {
...
};
}
componentDidMount() {
// return object state but with inital value {isConnected :true}
console.log(this.context);
//this.fetchData(this.state.page);
}
render() {
// here when I use this.context return object {isConnected:true/false} depends on internet connection status on device
return(
<FlatList
...
/>
)
}
}
...