该错误可能与打字和渲染中的隐式返回有关。解决此问题时,最终会得到如下结果:
const PrivateRoute = ({component, isAuthenticated, ...rest}: any) => { const routeComponent = (props: any) => ( isAuthenticated ? React.createElement(component, props) : <Redirect to={{pathname: '/login'}}/> ); return <Route {...rest} render={routeComponent}/>;};该组件可以这样使用:
<PrivateRoute path='/private' isAuthenticated={this.props.state.session.isAuthenticated} component={PrivateContainer}/>上面的解决方案有一些缺点。其中之一是您失去类型安全性。
最好扩展
Route组件是更好的主意。
import * as React from 'react';import {Redirect, Route, RouteProps} from 'react-router';export interface ProtectedRouteProps extends RouteProps { isAuthenticated: boolean; authenticationPath: string;}export class ProtectedRoute extends Route<ProtectedRouteProps> { public render() { let redirectPath: string = ''; if (!this.props.isAuthenticated) { redirectPath = this.props.authenticationPath; } if (redirectPath) { const renderComponent = () => (<Redirect to={{pathname: redirectPath}}/>); return <Route {...this.props} component={renderComponent} render={undefined}/>; } else { return <Route {...this.props}/>; } }}因此,您可以使用以下组件:
const defaultProtectedRouteProps: ProtectedRouteProps = { isAuthenticated: this.props.state.session.isAuthenticated, authenticationPath: '/login',};<ProtectedRoute {...defaultProtectedRouteProps} exact={true} path='/' component={ProtectedContainer}/>更新(2019年11月)
如果您喜欢编写功能组件,则可以采用非常相似的方式来完成。这也适用于React Router 5:
import * as React from 'react';import { Redirect, Route, RouteProps } from 'react-router';export interface ProtectedRouteProps extends RouteProps { isAuthenticated: boolean; isAllowed: boolean; restrictedPath: string; authenticationPath: string;}export const ProtectedRoute: React.FC<ProtectedRouteProps> = props => { let redirectPath = ''; if (!props.isAuthenticated) { redirectPath = props.authenticationPath; } if (props.isAuthenticated && !props.isAllowed) { redirectPath = props.restrictedPath; } if (redirectPath) { const renderComponent = () => <Redirect to={{ pathname: redirectPath }} />; return <Route {...props} component={renderComponent} render={undefined} />; } else { return <Route {...props} />; }};export default ProtectedRoute;更新(2019年12月)
如果要将用户重定向到该用户首先要访问的路径,则需要记住该路径,这样您就可以在成功通过身份验证后进行重定向。以下答案将指导您完成该任务:



