react-navigation用react Context包装根AppContainer

时间:2018-12-07 13:10:18

标签: reactjs react-native react-navigation

我正在寻找一种使用react-navigation在我的react-native应用程序中管理全局状态的方法。我尝试实现基本的React Context,我想将它包装在react-navigation的\0方法周围,但是它没有用。

我最终使用Context的HOC从createAppContainer()文件包装了一个应用程序容器,但是当Context的状态更改时,似乎反应导航在嵌套组件的重新渲染方面存在问题。我可以从嵌套的组件访问我的上下文,但是当上下文状态更改时,它们不会被重新渲染。

我的index.js文件如下:

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上下文状态的值,但是每当我切换互联网连接时(在android上模拟器)打开/关闭,上下文状态已更改,但未重新呈现组件,并且未触发我的isOnline方法。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

就我而言,我将React从16.8降级为16.5.0,React导航版本为3。 我仍在调查,但这只是暂时的解决方案。