react-navigation包装根AppContainer with react Context

问题描述 投票:1回答:1

我正在寻找使用react-navigation在我的react-native应用程序中管理全局状态的方法。我试图实现基本的React Context,我想围绕react-navigation的createAppContainer()方法,但它没有用。

我最终使用Context的HOC从index.js文件中包装了一个app容器,但是当Context的状态发生变化时,似乎反应导航在重新渲染嵌套组件方面存在问题。我可以从嵌套组件访问我的上下文,但是当上下文状态改变时它们不会被重新呈现。

我的index.js文件看起来像:

import { AppRegistry } from "react-native";
import App from "./src/App";
import { withAppContextProvider } from "./src/AppContext";
import { name as appName } from "./app.json";

AppRegistry.registerComponent(appName, () => withAppContextProvider(App));

我的上下文类看起来像:

// for new react static context API
export const AppContext = createContext({});

// create the consumer as higher order component
export const withAppContext = ChildComponent => props => (
  <AppContext.Consumer>
    {context => <ChildComponent {...props} global={context} />}
  </AppContext.Consumer>
);

// create the Provider as higher order component (only for root Component of the application)
export const withAppContextProvider = ChildComponent => props => (
  <AppContextProvider>
    <ChildComponent {...props} />
  </AppContextProvider>
);

export class AppContextProvider extends Component {
  state = {
    isOnline: true
  };

  handleConnectivityChange = isOnline => {
    this.setState({ isOnline });
  };

  componentDidMount = async () => {
    NetInfo.isConnected.addEventListener(
      "connectionChange",
      this.handleConnectivityChange
    );
  };

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener(
      "connectionChange",
      this.handleConnectivityChange
    );
  }

  render() {
    return (
      <AppContext.Provider
        value={{
          ...this.state
        }}
      >
        {this.props.children}
      </AppContext.Provider>
    );
  }
}

我的App.js文件看起来像:

const HomeStack = createStackNavigator(
  {
    Home: HomeScreen,
    Cities: CitiesScreen
  },
  getStackConfig({ initialRouteName: "Home" })
);

const SettingsStack = createStackNavigator(
  {
    Settings: SettingsScreen
  },
  getStackConfig({ initialRouteName: "Settings" })
);

export default createAppContainer(
  createBottomTabNavigator(
    {
      Home: HomeStack,
      Settings: SettingsStack
    }
  )
);

CitiesScreen组件示例:

import { AppContext } from "../AppContext";

class CitiesScreen extends Component {
  static contextType = AppContext;

  render() {
    return (
      <View style={styles.container}>
        <Text>This value should change on isOnline update: {this.context.isOnline}</Text>
      </View>
    );
  }
}

现在,当我访问Context时,例如CitiesScreen组件,我现在能够获得isOnline上下文状态的值,但每当我打开/关闭我的互联网连接(在Android模拟器上)时,上下文状态就会改变但是组件没有重新渲染,我的shouldComponentUpdate()方法没有被触发。有什么帮助使这项工作?

reactjs react-native react-navigation
1个回答
0
投票

在我的情况下,我将React从16.8降级到16.5.0,反应导航版本为3.我仍在调查,但这是暂时的解决方案。

热门问题
推荐问题
最新问题