我的自定义身份验证 react-router 路由有什么问题?

What is wrong with my custom authentication react-router route?

不幸的是,我无法使用 react-router version 4 创建自定义路由。如果用户通过身份验证或在其他情况下将用户重定向到登录组件,我正在尝试构建呈现组件的路由。

我一直在使用 this documentation page 开始。

const ProtectedRoute = ({component, ...rest}) => (
    <Route {...rest} render={props => false
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}}/>}
    />
);

我正在这样使用 ProtectedRoute

<ProtectedRoute exact path='/' component={testComponent}/>

当我运行这个时,我得到以下运行时间错误:

Uncaught ReferenceError: __rest is not defined
    at ProtectedRoute (index.tsx:19)
    at ReactCompositeComponent.js:305
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._constructComponentWithoutOwner (ReactCompositeComponent.js:304)
    at ReactCompositeComponentWrapper._constructComponent (ReactCompositeComponent.js:279)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:187)
    at Object.mountComponent (ReactReconciler.js:45)
    at ReactDOMComponent.mountChildren (ReactMultiChild.js:236)
    at ReactDOMComponent._createInitialChildren (ReactDOMComponent.js:703)
    at ReactDOMComponent.mountComponent (ReactDOMComponent.js:522)

这里有一些关于我正在使用的堆栈的更多信息:

为什么rest没有定义?我的自定义路线有什么问题?

提前致谢!

更新(最小示例)

可以找到问题的最小示例 here。要 运行 示例,请按照以下步骤操作:

我不是 Typescript 专家,也没有深入研究 TS,但这绝对是与您尝试使用 ...rest 运算符有关的问题。我猜 ts 不喜欢对象解构中的扩展运算符,因此不喜欢以下结构(尽管它在 ES6 中可以正常工作):

ProtectedRoute = ({component: Component, isAuthenticated, ...rest}) => {

如果您使用 path prop 的显式使用来重写您的组件,它会恢复正常工作。

const ProtectedRoute = ({component: Component, isAuthenticated, path}) => {
    return <Route
        path={path}
        render={props => isAuthenticated
            ? <Component {...props} />
            : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
}; 

但是你的代码不起作用这一事实对我来说似乎很奇怪,因为它提到从 2.1 版本开始打字稿在对象解构中支持 spread/rest:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#object-spread-and-rest

好的,我知道是怎么回事了。在您的 tsconfig.json 中,您声明了此规则 "noEmitHelpers": true ,它告诉打字稿编译器不要在输出中包含任何辅助函数,例如 __rest 。这就是 __rest is not defined 出现运行时错误的原因。将其更改为 false 应该可以解决您的问题。