Reactjs 我的自定义身份验证路由器路由有什么问题?

Reactjs 我的自定义身份验证路由器路由有什么问题?,reactjs,typescript,react-router,jsx,react-router-v4,Reactjs,Typescript,React Router,Jsx,React Router V4,不幸的是,我无法使用创建自定义路由。我正在尝试构造一个路由来呈现一个组件,如果用户经过身份验证,或者在另一种情况下将用户重定向到登录组件 我已经习惯了开始 const ProtectedRoute = ({component, ...rest}) => ( <Route {...rest} render={props => false ? <Component {...props} /> : <Redirect to={

不幸的是,我无法使用创建自定义路由。我正在尝试构造一个路由来呈现一个组件,如果用户经过身份验证,或者在另一种情况下将用户重定向到登录组件

我已经习惯了开始

const ProtectedRoute = ({component, ...rest}) => (
    <Route {...rest} render={props => false
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}}/>}
    />
);
运行此操作时,会出现以下运行时错误:

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)
下面是有关我使用的堆栈的更多信息:

  • 反应15.6.1
  • 反应路由器dom 4.2.2
  • 打字稿2.5.2
为什么
rest
没有定义?我的定制路线有什么问题

提前谢谢你

更新(最小示例) 可以找到这个问题的一个小例子。要运行该示例,请执行以下步骤:

  • 使用
    warn安装安装依赖项
  • 使用
    dev

我不是打字脚本专家,也没有深入研究TS,但这肯定是与您尝试使用
…rest
操作符有关的问题。我猜ts不喜欢对象分解中的spread操作符,因此也不喜欢以下结构(尽管它在ES6中可以正常工作):

如果您明确使用
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}}} />}
    />
}; 
const ProtectedRoute=({component:component,isAuthenticated,path})=>{
返回已验证
? 
: }
/>
}; 

但是您的代码不工作的事实对我来说似乎很奇怪,因为提到从2.1版开始,typescript支持对象分解中的spread/rest:

好的,我知道发生了什么。在
tsconfig.json
中,您声明了此规则
“noEmitHelpers”:true
,它告诉typescript编译器不要在输出中包含任何类似
\u rest
的帮助函数。这就是为什么
出现运行时错误\u未定义rest
。将其更改为
false
应该可以解决您的问题。

我的结构与您的结构相同,可以正常工作。你能提供一个简单的回购协议来重现你的问题吗?在您的代码中,您在组件拼写方面存在差异,您正在传递
组件
并使用
组件
,这可能是造成问题的原因。@niba感谢您的评论!我已经更新了我的问题并添加了一个最小的示例。你可以在这里找到。你的方法很有效,但我不明白为什么spread操作符不起作用。非常感谢!这就解决了问题!
ProtectedRoute = ({component: Component, isAuthenticated, ...rest}) => {
const ProtectedRoute = ({component: Component, isAuthenticated, path}) => {
    return <Route
        path={path}
        render={props => isAuthenticated
            ? <Component {...props} />
            : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
};