现在我有App.js
是我的初始页面。
我想从net_provide.js
收听互联网状态。
如果isConnected
为真,则APP.js
显示renderLoadingView()
如果没有,则APP.js
像下面的代码一样显示renderDisconnectView()
但是我不知道如何将isConnected从net_provide.js
传递到APP.js
谁能帮我?谢谢!
App.js
renderLoadingView() {
_aesDecryptWithMode(_aesEncryptWithMode('test'))
getFcmToken()
return (
<View style={ styles.container }>
<NetworkNotifier
offlineText="無網路連線"
onlineText="網路已連線"
position="top" />
<Network_provider/>
<Text>
Loading Events....
{ '\n' }
</Text>
</View>
)
}
renderDisconnectView() {
return (
<View style={ styles.container }>
<Network_provider/>
<Text>
diss
{ '\n' }
</Text>
</View>
)
}
问题在这里 this.props.Connected
render() {
return (
if (this.props.isConnected) {
return this.renderLoadingView();
}
if (!this.props.isConnected) {
return this.renderDisconnectView();
}
}
下面是network_provider.js
export class Network_provider extends React.PureComponent {
state = {
isConnected: true
};
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
}
handleConnectivityChange = isConnected => {
if (isConnected) {
this.setState({
isConnected
});
} else {
this.setState({
isConnected
});
}
};
render() {
return <App Connected={ this.state.isConnected } />;
}
}
答案 0 :(得分:0)
将this.props.isConnected
更改为this.props.Connected
,因为您要在Network_provider中传递名为Connected to App组件的道具
render() {
return (
if (this.props.Connected) {
return this.renderLoadingView();
}
if (!this.props.Connected) {
return this.renderDisconnectView();
}
);
}
如果传递给handleConnectivityChange
的值是布尔值,那么您可以像这样将其缩短。
handleConnectivityChange = isConnected => {
this.setState({
isConnected:isConnected
});
};
更新 在您的子组件中尝试此操作。首先设置初始状态,并使用componentDidUpdate检查道具是否已更改。像这样
this.state={
Connected:true //default value
}
componentDidUpdate(prevProps, prevState) {
if (this.props.Connected!== prevProps.Connected) {
this.setState({Connected:this.props.Connected})
}
}
render() {
return (
if (this.state.Connected) {
return this.renderLoadingView();
}
if (!this.state.Connected) {
return this.renderDisconnectView();
}
);
}
答案 1 :(得分:0)
您可以为此使用作为儿童功能模式。
network_provider.js
render() {
const { children } = this.props;
const { isConnected } = this.state;
return children && children({isConnected});
}
App.js
<Network_provider>
{({isConnected}) => {
if(isConnected) return this.renderDisconnectView();
return this.renderLoadingView();
}
}
</Network_provider>