【发布时间】:2018-12-07 13:10:17
【问题描述】:
我正在寻找使用 react-navigation 在我的 react-native 应用程序中管理全局状态的方法。我尝试实现基本的 React Context,我想将它包裹在 react-navigation 的 createAppContainer() 方法中,但它没有用。
我最终使用 Context 的 HOC 从 index.js 文件包装了一个应用程序容器,但是当 Context 的状态发生更改时,react-navigation 似乎存在重新渲染嵌套组件的问题。我可以从嵌套组件访问我的上下文,但它们只是在上下文状态更改时不会重新呈现。
我的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>
);
}
}
现在,当我从 CitiesScreen 组件访问 Context 时,我目前能够获取 isOnline 上下文状态的值,但是每当我打开我的互联网连接(在 android 模拟器上)时/关闭时,上下文状态会更改,但不会重新渲染组件,并且不会触发我的 shouldComponentUpdate() 方法。有什么帮助来完成这项工作吗?
【问题讨论】:
-
没人帮忙吗?
标签: reactjs react-native react-navigation