如何使用Apollo Client + React Router实现私有路由和基于用户状态的重定向?
How to use Apollo Client + React Router to implement private routes and redirection based on user status?
我使用 React Router 4 进行路由,使用 Apollo Client 进行数据获取和缓存。我需要根据以下标准实施 PrivateRoute 和重定向解决方案:
允许用户查看的页面基于他们的用户状态,可以从服务器获取,也可以从缓存中读取。用户状态本质上是一组标志,我们用来了解用户在我们的渠道中的位置。标志示例:isLoggedIn
、isOnboarded
、isWaitlisted
等
如果用户的状态不允许他们出现在该页面上,则任何页面都不应开始呈现。例如,如果您不是 isWaitlisted
,则不应看到候补名单页面。当用户不小心发现自己在这些页面上时,应该将他们重定向到适合其状态的页面。
重定向也应该是动态的。例如,假设您在 isLoggedIn
之前尝试查看您的用户个人资料。然后我们需要将您重定向到登录页面。但是,如果您是 isLoggedIn
而不是 isOnboarded
,我们仍然不希望您看到您的个人资料。所以我们想将您重定向到入职页面。
所有这些都需要在路由级别发生。页面本身应该不知道这些权限和重定向。
总而言之,我们需要一个给定用户状态数据的库,可以
- 计算用户是否可以在某个页面上
- 计算需要动态重定向到的位置
- 在呈现任何页面之前执行这些操作
- 在路线级别执行这些操作
我已经在开发一个通用库,但它现在有它的缺点。我正在就应该如何解决这个问题以及是否存在实现这一目标的既定模式征求意见。
这是我目前的做法。这不起作用,因为 getRedirectPath
需要的数据在 OnboardingPage component
中。
另外,我不能用 HOC 包装 PrivateRoute,因为它不再是路线.
<PrivateRoute
exact
path="/onboarding"
isRender={(props) => {
return props.userStatus.isLoggedIn && props.userStatus.isWaitlistApproved;
}}
getRedirectPath={(props) => {
if (!props.userStatus.isLoggedIn) return '/login';
if (!props.userStatus.isWaitlistApproved) return '/waitlist';
}}
component={OnboardingPage}
/>
我认为您需要将您的逻辑向下移动一点。类似于:
<Route path="/onboarding" render={renderProps=>
<CheckAuthorization authorized={OnBoardingPage} renderProps={renderProps} />
}/>
您将不得不在没有 'react-graphql' HOC 的情况下使用 ApolloClient。
1.获取ApolloClient实例
2. 火查询
3. 当查询 returns 数据呈现加载时..
4.根据数据检查并授权路由。
5. Return 适当的组件或重定向。
这可以通过以下方式完成:
import Loadable from 'react-loadable'
import client from '...your ApolloClient instance...'
const queryPromise = client.query({
query: Storequery,
variables: {
name: context.params.sellername
}
})
const CheckedComponent = Loadable({
loading: LoadingComponent,
loader: () => new Promise((resolve)=>{
queryPromise.then(response=>{
/*
check response data and resolve appropriate component.
if matching error return redirect. */
if(response.data.userStatus.isLoggedIn){
resolve(ComponentToBeRendered)
}else{
resolve(<Redirect to={somePath}/>)
}
})
}),
})
<Route path="/onboarding" component={CheckedComponent} />
相关API参考:
https://www.apollographql.com/docs/react/reference/index.html
我个人习惯像这样构建我的私有路由:
const renderMergedProps = (component, ...rest) => {
const finalProps = Object.assign({}, ...rest);
return React.createElement(component, finalProps);
};
const PrivateRoute = ({
component, redirectTo, path, ...rest
}) => (
<Route
{...rest}
render={routeProps =>
(loggedIn() ? (
renderMergedProps(component, routeProps, rest)
) : (
<Redirect to={redirectTo} from={path} />
))
}
/>
);
在这种情况下,loggedIn()
是一个简单的函数,如果用户登录(取决于您处理用户会话的方式),return 为真,您可以像这样创建每个私有路由.
然后你可以在 Switch 中使用它:
<Switch>
<Route path="/login" name="Login" component={Login} />
<PrivateRoute
path="/"
name="Home"
component={App}
redirectTo="/login"
/>
</Switch>
来自此 PrivateRoute
的所有子路由首先需要检查用户是否已登录。
最后一步是根据所需状态嵌套路由。
一般方法
我会创建一个 HOC 来处理您所有页面的这种逻辑。
// privateRoute is a function...
const privateRoute = ({
// ...that takes optional boolean parameters...
requireLoggedIn = false,
requireOnboarded = false,
requireWaitlisted = false
// ...and returns a function that takes a component...
} = {}) => WrappedComponent => {
class Private extends Component {
componentDidMount() {
// redirect logic
}
render() {
if (
(requireLoggedIn && /* user isn't logged in */) ||
(requireOnboarded && /* user isn't onboarded */) ||
(requireWaitlisted && /* user isn't waitlisted */)
) {
return null
}
return (
<WrappedComponent {...this.props} />
)
}
}
Private.displayName = `Private(${
WrappedComponent.displayName ||
WrappedComponent.name ||
'Component'
})`
hoistNonReactStatics(Private, WrappedComponent)
// ...and returns a new component wrapping the parameter component
return Private
}
export default privateRoute
那你只需要改变导出路由的方式:
export default privateRoute({ requireLoggedIn: true })(MyRoute);
并且您可以像今天在 react-router:
中一样使用该路线
<Route path="/" component={MyPrivateRoute} />
重定向逻辑
如何设置这部分取决于几个因素:
- 您如何确定用户是否已登录、已加入、已列入候补名单等
- 您要负责要重定向到的哪个组件。
处理用户状态
由于您使用的是 Apollo,您可能只想使用 graphql
在 HOC 中获取该数据:
return graphql(gql`
query ...
`)(Private)
然后你可以修改Private
组件来获取这些道具:
class Private extends Component {
componentDidMount() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
}
} = this.props
if (requireLoggedIn && !isLoggedIn) {
// redirect somewhere
} else if (requireOnboarded && !isOnboarded) {
// redirect somewhere else
} else if (requireWaitlisted && !isWaitlisted) {
// redirect to yet another location
}
}
render() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
...passThroughProps
} = this.props
if (
(requireLoggedIn && !isLoggedIn) ||
(requireOnboarded && !isOnboarded) ||
(requireWaitlisted && !isWaitlisted)
) {
return null
}
return (
<WrappedComponent {...passThroughProps} />
)
}
}
重定向到哪里
您可以在几个不同的地方处理此问题。
简单方法:路由是静态的
如果用户未登录,您总是希望路由到 /login?return=${currentRoute}
。
在这种情况下,您可以在 componentDidMount
中硬编码这些路由。完成。
组件负责
如果你想让你的MyRoute
组件确定路径,你可以在你的privateRoute
函数中添加一些额外的参数,然后在导出MyRoute
时传入它们。
const privateRoute = ({
requireLoggedIn = false,
pathIfNotLoggedIn = '/a/sensible/default',
// ...
}) // ...
然后,如果您想覆盖默认路径,请将导出更改为:
export default privateRoute({
requireLoggedIn: true,
pathIfNotLoggedIn: '/a/specific/page'
})(MyRoute)
路由负责
如果您希望能够从路由中传递路径,您需要在 Private
中接收这些道具
class Private extends Component {
componentDidMount() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted
} = this.props
if (requireLoggedIn && !isLoggedIn) {
// redirect to `pathIfNotLoggedIn`
} else if (requireOnboarded && !isOnboarded) {
// redirect to `pathIfNotOnboarded`
} else if (requireWaitlisted && !isWaitlisted) {
// redirect to `pathIfNotWaitlisted`
}
}
render() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
// we don't care about these for rendering, but we don't want to pass them to WrappedComponent
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted,
...passThroughProps
} = this.props
if (
(requireLoggedIn && !isLoggedIn) ||
(requireOnboarded && !isOnboarded) ||
(requireWaitlisted && !isWaitlisted)
) {
return null
}
return (
<WrappedComponent {...passThroughProps} />
)
}
}
Private.propTypes = {
pathIfNotLoggedIn: PropTypes.string
}
Private.defaultProps = {
pathIfNotLoggedIn: '/a/sensible/default'
}
那么你的路线可以改写为:
<Route path="/" render={props => <MyPrivateComponent {...props} pathIfNotLoggedIn="/a/specific/path" />} />
合并选项 2 和 3
(这是我喜欢使用的方法)
你也可以让组件和路由选择谁负责。您只需要为路径添加 privateRoute
参数,就像我们为让组件决定所做的那样。然后使用这些值作为您的 defaultProps
就像我们在路由负责时所做的那样。
这使您可以灵活地做出决定。请注意,将路由作为 props 传递将优先于从组件传递到 HOC。
大家在一起
这里有一段结合了上面所有概念的片段,用于最终实现 HOC:
const privateRoute = ({
requireLoggedIn = false,
requireOnboarded = false,
requireWaitlisted = false,
pathIfNotLoggedIn = '/login',
pathIfNotOnboarded = '/onboarding',
pathIfNotWaitlisted = '/waitlist'
} = {}) => WrappedComponent => {
class Private extends Component {
componentDidMount() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted
} = this.props
if (requireLoggedIn && !isLoggedIn) {
// redirect to `pathIfNotLoggedIn`
} else if (requireOnboarded && !isOnboarded) {
// redirect to `pathIfNotOnboarded`
} else if (requireWaitlisted && !isWaitlisted) {
// redirect to `pathIfNotWaitlisted`
}
}
render() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted,
...passThroughProps
} = this.props
if (
(requireLoggedIn && !isLoggedIn) ||
(requireOnboarded && !isOnboarded) ||
(requireWaitlisted && !isWaitlisted)
) {
return null
}
return (
<WrappedComponent {...passThroughProps} />
)
}
}
Private.propTypes = {
pathIfNotLoggedIn: PropTypes.string,
pathIfNotOnboarded: PropTypes.string,
pathIfNotWaitlisted: PropTypes.string
}
Private.defaultProps = {
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted
}
Private.displayName = `Private(${
WrappedComponent.displayName ||
WrappedComponent.name ||
'Component'
})`
hoistNonReactStatics(Private, WrappedComponent)
return graphql(gql`
query ...
`)(Private)
}
export default privateRoute
我正在使用 hoist-non-react-statics as suggested in the official documentation。
如果您使用的是 apollo react 客户端,您还可以导入 Query
@apollo/components
并在您的私有路由中像这样使用它:
<Query query={fetchUserInfoQuery(moreUserInfo)}>
{({ loading, error, data: userInfo = {} }: any) => {
const isNotAuthenticated = !loading && (isEmpty(userInfo) || !userInfo.whoAmI);
if (isNotAuthenticated || error) {
return <Redirect to={RoutesPaths.Login} />;
}
const { whoAmI } = userInfo;
return <Component user={whoAmI} {...renderProps} />;
}}
</Query>
其中 isEmpty
只是检查给定对象是否为空:
const isEmpty = (object: any) => object && Object.keys(object).length === 0
我使用 React Router 4 进行路由,使用 Apollo Client 进行数据获取和缓存。我需要根据以下标准实施 PrivateRoute 和重定向解决方案:
允许用户查看的页面基于他们的用户状态,可以从服务器获取,也可以从缓存中读取。用户状态本质上是一组标志,我们用来了解用户在我们的渠道中的位置。标志示例:
isLoggedIn
、isOnboarded
、isWaitlisted
等如果用户的状态不允许他们出现在该页面上,则任何页面都不应开始呈现。例如,如果您不是
isWaitlisted
,则不应看到候补名单页面。当用户不小心发现自己在这些页面上时,应该将他们重定向到适合其状态的页面。重定向也应该是动态的。例如,假设您在
isLoggedIn
之前尝试查看您的用户个人资料。然后我们需要将您重定向到登录页面。但是,如果您是isLoggedIn
而不是isOnboarded
,我们仍然不希望您看到您的个人资料。所以我们想将您重定向到入职页面。所有这些都需要在路由级别发生。页面本身应该不知道这些权限和重定向。
总而言之,我们需要一个给定用户状态数据的库,可以
- 计算用户是否可以在某个页面上
- 计算需要动态重定向到的位置
- 在呈现任何页面之前执行这些操作
- 在路线级别执行这些操作
我已经在开发一个通用库,但它现在有它的缺点。我正在就应该如何解决这个问题以及是否存在实现这一目标的既定模式征求意见。
这是我目前的做法。这不起作用,因为 getRedirectPath
需要的数据在 OnboardingPage component
中。
另外,我不能用 HOC 包装 PrivateRoute,因为它不再是路线.
<PrivateRoute
exact
path="/onboarding"
isRender={(props) => {
return props.userStatus.isLoggedIn && props.userStatus.isWaitlistApproved;
}}
getRedirectPath={(props) => {
if (!props.userStatus.isLoggedIn) return '/login';
if (!props.userStatus.isWaitlistApproved) return '/waitlist';
}}
component={OnboardingPage}
/>
我认为您需要将您的逻辑向下移动一点。类似于:
<Route path="/onboarding" render={renderProps=>
<CheckAuthorization authorized={OnBoardingPage} renderProps={renderProps} />
}/>
您将不得不在没有 'react-graphql' HOC 的情况下使用 ApolloClient。
1.获取ApolloClient实例
2. 火查询
3. 当查询 returns 数据呈现加载时..
4.根据数据检查并授权路由。
5. Return 适当的组件或重定向。
这可以通过以下方式完成:
import Loadable from 'react-loadable'
import client from '...your ApolloClient instance...'
const queryPromise = client.query({
query: Storequery,
variables: {
name: context.params.sellername
}
})
const CheckedComponent = Loadable({
loading: LoadingComponent,
loader: () => new Promise((resolve)=>{
queryPromise.then(response=>{
/*
check response data and resolve appropriate component.
if matching error return redirect. */
if(response.data.userStatus.isLoggedIn){
resolve(ComponentToBeRendered)
}else{
resolve(<Redirect to={somePath}/>)
}
})
}),
})
<Route path="/onboarding" component={CheckedComponent} />
相关API参考: https://www.apollographql.com/docs/react/reference/index.html
我个人习惯像这样构建我的私有路由:
const renderMergedProps = (component, ...rest) => {
const finalProps = Object.assign({}, ...rest);
return React.createElement(component, finalProps);
};
const PrivateRoute = ({
component, redirectTo, path, ...rest
}) => (
<Route
{...rest}
render={routeProps =>
(loggedIn() ? (
renderMergedProps(component, routeProps, rest)
) : (
<Redirect to={redirectTo} from={path} />
))
}
/>
);
在这种情况下,loggedIn()
是一个简单的函数,如果用户登录(取决于您处理用户会话的方式),return 为真,您可以像这样创建每个私有路由.
然后你可以在 Switch 中使用它:
<Switch>
<Route path="/login" name="Login" component={Login} />
<PrivateRoute
path="/"
name="Home"
component={App}
redirectTo="/login"
/>
</Switch>
来自此 PrivateRoute
的所有子路由首先需要检查用户是否已登录。
最后一步是根据所需状态嵌套路由。
一般方法
我会创建一个 HOC 来处理您所有页面的这种逻辑。
// privateRoute is a function...
const privateRoute = ({
// ...that takes optional boolean parameters...
requireLoggedIn = false,
requireOnboarded = false,
requireWaitlisted = false
// ...and returns a function that takes a component...
} = {}) => WrappedComponent => {
class Private extends Component {
componentDidMount() {
// redirect logic
}
render() {
if (
(requireLoggedIn && /* user isn't logged in */) ||
(requireOnboarded && /* user isn't onboarded */) ||
(requireWaitlisted && /* user isn't waitlisted */)
) {
return null
}
return (
<WrappedComponent {...this.props} />
)
}
}
Private.displayName = `Private(${
WrappedComponent.displayName ||
WrappedComponent.name ||
'Component'
})`
hoistNonReactStatics(Private, WrappedComponent)
// ...and returns a new component wrapping the parameter component
return Private
}
export default privateRoute
那你只需要改变导出路由的方式:
export default privateRoute({ requireLoggedIn: true })(MyRoute);
并且您可以像今天在 react-router:
中一样使用该路线<Route path="/" component={MyPrivateRoute} />
重定向逻辑
如何设置这部分取决于几个因素:
- 您如何确定用户是否已登录、已加入、已列入候补名单等
- 您要负责要重定向到的哪个组件。
处理用户状态
由于您使用的是 Apollo,您可能只想使用 graphql
在 HOC 中获取该数据:
return graphql(gql`
query ...
`)(Private)
然后你可以修改Private
组件来获取这些道具:
class Private extends Component {
componentDidMount() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
}
} = this.props
if (requireLoggedIn && !isLoggedIn) {
// redirect somewhere
} else if (requireOnboarded && !isOnboarded) {
// redirect somewhere else
} else if (requireWaitlisted && !isWaitlisted) {
// redirect to yet another location
}
}
render() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
...passThroughProps
} = this.props
if (
(requireLoggedIn && !isLoggedIn) ||
(requireOnboarded && !isOnboarded) ||
(requireWaitlisted && !isWaitlisted)
) {
return null
}
return (
<WrappedComponent {...passThroughProps} />
)
}
}
重定向到哪里
您可以在几个不同的地方处理此问题。
简单方法:路由是静态的
如果用户未登录,您总是希望路由到 /login?return=${currentRoute}
。
在这种情况下,您可以在 componentDidMount
中硬编码这些路由。完成。
组件负责
如果你想让你的MyRoute
组件确定路径,你可以在你的privateRoute
函数中添加一些额外的参数,然后在导出MyRoute
时传入它们。
const privateRoute = ({
requireLoggedIn = false,
pathIfNotLoggedIn = '/a/sensible/default',
// ...
}) // ...
然后,如果您想覆盖默认路径,请将导出更改为:
export default privateRoute({
requireLoggedIn: true,
pathIfNotLoggedIn: '/a/specific/page'
})(MyRoute)
路由负责
如果您希望能够从路由中传递路径,您需要在 Private
class Private extends Component {
componentDidMount() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted
} = this.props
if (requireLoggedIn && !isLoggedIn) {
// redirect to `pathIfNotLoggedIn`
} else if (requireOnboarded && !isOnboarded) {
// redirect to `pathIfNotOnboarded`
} else if (requireWaitlisted && !isWaitlisted) {
// redirect to `pathIfNotWaitlisted`
}
}
render() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
// we don't care about these for rendering, but we don't want to pass them to WrappedComponent
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted,
...passThroughProps
} = this.props
if (
(requireLoggedIn && !isLoggedIn) ||
(requireOnboarded && !isOnboarded) ||
(requireWaitlisted && !isWaitlisted)
) {
return null
}
return (
<WrappedComponent {...passThroughProps} />
)
}
}
Private.propTypes = {
pathIfNotLoggedIn: PropTypes.string
}
Private.defaultProps = {
pathIfNotLoggedIn: '/a/sensible/default'
}
那么你的路线可以改写为:
<Route path="/" render={props => <MyPrivateComponent {...props} pathIfNotLoggedIn="/a/specific/path" />} />
合并选项 2 和 3
(这是我喜欢使用的方法)
你也可以让组件和路由选择谁负责。您只需要为路径添加 privateRoute
参数,就像我们为让组件决定所做的那样。然后使用这些值作为您的 defaultProps
就像我们在路由负责时所做的那样。
这使您可以灵活地做出决定。请注意,将路由作为 props 传递将优先于从组件传递到 HOC。
大家在一起
这里有一段结合了上面所有概念的片段,用于最终实现 HOC:
const privateRoute = ({
requireLoggedIn = false,
requireOnboarded = false,
requireWaitlisted = false,
pathIfNotLoggedIn = '/login',
pathIfNotOnboarded = '/onboarding',
pathIfNotWaitlisted = '/waitlist'
} = {}) => WrappedComponent => {
class Private extends Component {
componentDidMount() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted
} = this.props
if (requireLoggedIn && !isLoggedIn) {
// redirect to `pathIfNotLoggedIn`
} else if (requireOnboarded && !isOnboarded) {
// redirect to `pathIfNotOnboarded`
} else if (requireWaitlisted && !isWaitlisted) {
// redirect to `pathIfNotWaitlisted`
}
}
render() {
const {
userStatus: {
isLoggedIn,
isOnboarded,
isWaitlisted
},
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted,
...passThroughProps
} = this.props
if (
(requireLoggedIn && !isLoggedIn) ||
(requireOnboarded && !isOnboarded) ||
(requireWaitlisted && !isWaitlisted)
) {
return null
}
return (
<WrappedComponent {...passThroughProps} />
)
}
}
Private.propTypes = {
pathIfNotLoggedIn: PropTypes.string,
pathIfNotOnboarded: PropTypes.string,
pathIfNotWaitlisted: PropTypes.string
}
Private.defaultProps = {
pathIfNotLoggedIn,
pathIfNotOnboarded,
pathIfNotWaitlisted
}
Private.displayName = `Private(${
WrappedComponent.displayName ||
WrappedComponent.name ||
'Component'
})`
hoistNonReactStatics(Private, WrappedComponent)
return graphql(gql`
query ...
`)(Private)
}
export default privateRoute
我正在使用 hoist-non-react-statics as suggested in the official documentation。
如果您使用的是 apollo react 客户端,您还可以导入 Query
@apollo/components
并在您的私有路由中像这样使用它:
<Query query={fetchUserInfoQuery(moreUserInfo)}>
{({ loading, error, data: userInfo = {} }: any) => {
const isNotAuthenticated = !loading && (isEmpty(userInfo) || !userInfo.whoAmI);
if (isNotAuthenticated || error) {
return <Redirect to={RoutesPaths.Login} />;
}
const { whoAmI } = userInfo;
return <Component user={whoAmI} {...renderProps} />;
}}
</Query>
其中 isEmpty
只是检查给定对象是否为空:
const isEmpty = (object: any) => object && Object.keys(object).length === 0