我创建了Application实例,如下所示。
import { NetInfo } from 'react-native'
function App() {
this.flag = {
isConnected: false
}
...
return () => {
NetInfo.addEventListener(
'connectionChange',
(__connectionInfo) => {
if (__connectionInfo is not empty) {
// check if network connection type is available
// or not if not found than re-update flag to false.
if (__connectionInfo.type !== 'none' && __connectionInfo.effectiveType !== 'unknown') {
// update flag.
this.flag.isConnected = true // <-- should be updated to App(this). if you try App.flag.isConnected it will return false
} else {
// update false network.
this.flag.isConnected = false
}
}
}) // network event listener.
}
}
// calling instance.
let _morphine = new App()
_morphine = _morphine() <--- I am just importing this already created instance in every component for using it as system core handler for handling every task like saving data, updating notify network change using instance.
*在实际代码中,我已经将_morphine对象包装到if else中,以便无论何时在用户设备上首次启动应用程序,都只创建一个实例。
问题: 1.我想在网络更改时重新渲染布局组件,但似乎网络侦听器没有将this.flag.isConnected更新为true || false。2.以上通过组件共享系统核心的模式在使用单实例时是好的吗?
发布于 2018-12-17 03:46:27
根据NetInfo Example,您的事件侦听器应该如下所示...
NetInfo.addEventListener('change', this._handleConnectionInfoChange);
发布于 2018-12-17 05:05:25
您在一个普通函数中使用了this
(您的App
组件返回一个普通函数,而不是箭头函数)。该this
是从它被调用的上下文中求值的。例如,在全局空间中调用它,就像您在代码片段中所做的那样,将使this
成为global
,而this.isConnected
将是未定义的。您有两个选项来解决此问题:
App
中返回箭头函数。Arrow function将this
绑定到它声明的作用域,因此您将拥有一个常量,使用this
并只使用普通闭包,将isConnected
声明为函数变量,您返回的函数将可以访问它。关于单例设计的问题,就我个人而言,我更喜欢做一个有内部状态isConnected
的组件。事件处理程序可以放在componentDidMount
和componentWillUnmount
中。然后,您可以使用render props模式访问连接状态
class NetInfo extends Component {
state = {isConnected: false}
componentDidMount() {
// set up event listener
}
componentWillUnmount() {
// remove event listener
}
render() {
return this.props.children(this.state.isConnected)
}
}
https://stackoverflow.com/questions/53805111
复制相似问题