2016年11月3日 星期四

Netinfo in React Native

20161103 Netinfo in React Native

React Native 判斷 NetInfo 這部份的 API 在兩個平台上不大相容

變得有點奇怪

參考這裡面的作法

src/actions/network.js

setIsConnected: (isConnected: boolean): Action => ({
type: 'setIsConnected',
isConnected,
}),
setConnectType: (connectType: string): Action => ({
type: 'setConnectType',
connectType,
}),

src/reducer/network.js

add corresponding reducer

src/entry.js

constructor(props) {
super(props);
// force reset otherwise could be a problem in persist storage
this.props.actions.setIsConnected(false);
this.props.actions.setConnectType(undefined);
}
componentDidMount() {
NetInfo.addEventListener('change', this.dispatchConnected);
// iOS doesn't have to do this
NetInfo.fetch().done(
connectType => this.dispatchConnected(connectType)
);
}
componentWillUnmount() {
NetInfo.removeEventListener('change', this.dispatchConnected);
}
dispatchConnected = (connectType) => {
let isConnected = false;
if (connectType.toLowerCase() !== 'none' && connectType.toLowerCase() !== 'unknown') {
isConnected = true;
}
this.props.actions.setIsConnected(isConnected);
this.props.actions.setConnectType(connectType);
};

Usage

store.network.isConnect boolean
store.network.connectType string

it could be undefined