在启动应用程序时,我有一个初始屏幕。显示飞溅时,我使用asyncStorage
检索了一些数据。我想将该数据保存到我的商店。因此,我将App.ts
组件这样连接到了商店:
const mapDispatchToProps = (dispatch:any) => ({
setTokenValidity: (isTokenValid:boolean) => dispatch(setTokenValidity(isTokenValid))
})
const mapStateToProps = (state:any) => ({
isTokenValid: state.isTokenValid
})
export default connect(mapStateToProps, mapDispatchToProps)(App);
这是App.ts
的其余设置:
const Stack = createStackNavigator();
let userToken = null;
const App = (props:any) => {
const [IsSignedIn, setIsSignedIn] = useState(false);
useEffect(() => {
const bootstrapAsync = async () => {
try {
userToken = await retrieveData('Token',null);
SplashScreen.hide();
if(userToken != null) {
setIsSignedIn(true);
props.setTokenValidity(true)
}
} catch (e) {
// Restoring token failed
}
};
bootstrapAsync();
}, []);
return (
<Provider store={storeFactory()}>
<NavigationContainer>
<Stack.Navigator >
{!props.isTokenValid ? (
<>
<Stack.Screen name="Login" component={Login} options={{ headerShown:false }}/>
<Stack.Screen name="Home" component={Home} options={{ headerShown:false }}/>
</>
) : (
<Stack.Screen name="Home" component={Home} options={{ headerShown:false }}/>
)}
</Stack.Navigator >
</NavigationContainer>
</Provider>
);
};
运行应用程序时出现错误提示:
Could not find "store" in the context of "Conenct(App)". Either wrap the root component in a <Provider> or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(App) in connect options.
我的问题是,是否可以在此顶层连接到商店,还是只能在子组件中完成?
答案 0 :(得分:2)
如您所说,只能在子组件中完成。要在App
上使用connect,您需要将<Provider>
元素在层次结构中上移一层。通常,您会使用某种<Root>
元素来设置商店,然后将App
用作其后代。