gpt4 book ai didi

javascript - 使用 Redux 通过 React-Navigation(v.3 或 v.4)制作 protected 路线

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:10:34 26 4
gpt4 key购买 nike

我们如何使用 redux 在 react-navigation 中创建 protected 路由?

假设我有一个包含以下状态的 redux store

const mapStateToProps = state => {
return {
isAuthenticated: state.profileInfo.isAuthenticated,
isLoaded: state.profileInfo.isLoaded,
googleProfileLoading: state.profileInfo.googleProfileLoading
}
};

我正在使用 React-navigation 来导航用户。

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);

现在,如果用户未登录,我想重定向到登录屏幕。

在简单的 react-redux 中,这是我通常做的:https://github.com/irohitb/SelfieApp/blob/master/client/src/routes.js

谁能帮我弄清楚我们如何在 react-native、redux 和 react-navigation 中创建 protected 路由

最佳答案

react-navigation 有 createSwitchNavigator 正是为了这样的情况 Authentication Flow .

您必须将 protected 路由分组到一个 MainStack 中。使用 createStackNavigator:

const MainStack = createStackNavigator(
{
home: { screen: HomeScreen },
events: { screen: EventsScreen },
profile: { screen: ProfileScreen },
...
{
initialRouteName: "home"
}
);

然后,再次使用 createStackNavigator 配置您的身份验证堆栈:

const AuthStack = createStackNavigator({
login: { screen: LoginScreen },
register: { screen: RegisterScreen },
forgot: { screen: ForgottenPasswordScreen },
...
});

现在是 createSwitchNavigator - 加载 MainStack 堆栈或 AuthStack:

const Routes = createSwitchNavigator({
initialLoading: InitialLoadingScreen,
auth: AuthStack,
all: MainStack,
}, {
initialRouteName: 'initialLoading',
});

export default createAppContainer(Routes);

createSwitchNavigator 将加载 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);

如您所见,您可以将 InitialLoadingScreen 连接到 redux 存储,以访问任何数据并将其用于您的路由逻辑:)

关于javascript - 使用 Redux 通过 React-Navigation(v.3 或 v.4)制作 protected 路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55126897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com