iRo*_*tia 3 javascript reactjs react-native redux react-navigation
我们如何使用redux在react-navigation中创建受保护的路由?
考虑我有一个包含以下状态的redux存储
const mapStateToProps = state => {
return {
isAuthenticated: state.profileInfo.isAuthenticated,
isLoaded: state.profileInfo.isLoaded,
googleProfileLoading: state.profileInfo.googleProfileLoading
}
};
Run Code Online (Sandbox Code Playgroud)
我正在使用React导航来导航用户。
const loginNavigation = createStackNavigator(
{
login: {
screen: Login
},
signup: {
screen: Signup
}
},
{
headerMode: "none"
}
)
const allRoutes = createSwitchNavigator(
{
home: {
screen: loginNavigation
},
user: {
screen: user
},
{
initialRouteName: "home"
}
);
const App = createAppContainer(allRoutes);
Run Code Online (Sandbox Code Playgroud)
现在,如果用户尚未登录,我想重定向到登录屏幕。
在简单的react-redux中,这通常是我通常要做的事情:https : //github.com/irohitb/SelfieApp/blob/master/client/src/routes.js
有人可以帮我弄清楚我们如何在react-native,redux和react-navigation中创建受保护的路由
react-navigation createSwitchNavigator正是针对这种Authentication Flow的情况。
您必须将受保护的路由分组到一个MainStack中。用途createStackNavigator:
const MainStack = createStackNavigator(
{
home: { screen: HomeScreen },
events: { screen: EventsScreen },
profile: { screen: ProfileScreen },
...
{
initialRouteName: "home"
}
);
Run Code Online (Sandbox Code Playgroud)
然后,再次使用来配置身份验证堆栈createStackNavigator:
const AuthStack = createStackNavigator({
login: { screen: LoginScreen },
register: { screen: RegisterScreen },
forgot: { screen: ForgottenPasswordScreen },
...
});
Run Code Online (Sandbox Code Playgroud)
现在来了createSwitchNavigator-加载MainStack堆栈或AuthStack-
const Routes = createSwitchNavigator({
initialLoading: InitialLoadingScreen,
auth: AuthStack,
all: MainStack,
}, {
initialRouteName: 'initialLoading',
});
export default createAppContainer(Routes);
Run Code Online (Sandbox Code Playgroud)
无论用户是否通过身份验证,createSwitchNavigatorwill加载InitialLoadingScreen都会保存逻辑:
class InitialLoadingScreen extends React.Component {
constructor(props) {
super(props);
this.bootstrapAsync();
}
bootstrapAsync = async () => {
// Load the home screen for the logged in users
if (this.props.isAuthenticated) {
return this.props.navigation.navigate('home');
}
// load the Auth screen if the user is NOT logged in
this.props.navigation.navigate('login');
}
// Render any loading content that you like here
render() {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
}
}
const mapStateToProps = ({ settings }) => ({
isAuthenticated: state.profileInfo.isAuthenticated,
isLoaded: state.profileInfo.isLoaded,
googleProfileLoading: state.profileInfo.googleProfileLoading
});
export default connect(mapStateToProps)(InitialLoadingScreen);
Run Code Online (Sandbox Code Playgroud)
如您所见,您可以连接InitialLoadingScreen到redux存储,以访问任何数据并将其用于路由逻辑:)
| 归档时间: |
|
| 查看次数: |
503 次 |
| 最近记录: |