如何将上下文传递给组件

时间:2019-05-28 08:24:37

标签: reactjs react-native

我对下面的上下文有疑问。

这是NetworkProvider.js提供的互联网雕像

import React 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
  };

  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>
      );
  }
}

这是ExampleComponent.js

import React from 'react';
import { View, Text } from 'react-native';

import { NetworkContext } from './network_provider';

export class ExampleComponent extends React.PureComponent {
  static contextType = NetworkContext;

  render() {
    return (
      <View>
        <Text>
          You are now
          { this.context.isConnected ? 'online' : 'offline' }
        </Text>
      </View>
      );
  }
}

App.js

 static contextType = NetworkContext;
  render() {
    return (
      <NetworkProvider>
        <ExampleComponent />

        <View>
          <Text>
            You are now
            { this.context.isConnected ? 'online' : 'offline' }
          </Text>
        </View>
      </NetworkProvider>

      );
  }
}

如果我打开/关闭wifi,ExampleComponent.js是正确的 但是从ExampleComponent.js复制代码并不总是在线! 为什么要修改呢? 谢谢!

1 个答案:

答案 0 :(得分:0)

由于您正在监听connectionChange事件,因此此代码仅在连接更改时有效。

要一次收听网络连接,请使用此:

NetInfo.fetch().then(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});