Javascript 为什么自定义保护路由器不能呈现组件?
我有几个组件来保护身份验证。然后我制作了一个名为Javascript 为什么自定义保护路由器不能呈现组件?,javascript,reactjs,Javascript,Reactjs,我有几个组件来保护身份验证。然后我制作了一个名为ProtectedRoute的新组件。在这个ProtectedRoute函数中,我只捕获抛出的属性,但不知何故,我只从React Context获取状态,并且我发送的道具在console.log()中是未定义的 ProtectedRoute.js: import React from 'react' import { Route, Redirect } from 'react-router-dom' import { withAuth } from
ProtectedRoute
的新组件。在这个ProtectedRoute
函数中,我只捕获抛出的属性,但不知何故,我只从React Context
获取状态,并且我发送的道具在console.log()
中是未定义的
ProtectedRoute.js:
import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { withAuth } from './Context/AuthContext'
function ProtectedRoute(props) {
const {component: Component, ...rest} = props
console.log(Component)
return(
props.isLoggedIn ? <Route {...rest} component={Component} /> : <Redirect push to="/" />
)
}
export default withAuth(ProtectedRoute)
从“React”导入React
从“react router dom”导入{Route,Redirect}
从“./Context/AuthContext”导入{withAuth}
功能保护路线(道具){
常量{component:component,…rest}=props
console.log(组件)
返回(
道具。伊斯洛格丁?:
)
}
使用Auth导出默认值(ProtectedRoute)
App.js:
render() {
return (
<BrowserRouter>
<AuthContextProvider>
<Switch>
<Route exact path="/" component={Login} />
<ProtectedRoute path="/portal" component={Main} />
</Switch>
</AuthContextProvider>
</BrowserRouter>
)
}
render(){
返回(
)
}
顺便说一句,我已经导入了所有必需的组件,但是如果我通过react router
将ProtectedRoute
更改为normal
,它可以呈现组件Main
我的代码有问题吗?请尝试返回props.isLoggedIn:}/>你好,谢谢你的回复。它给出了超出最大更新深度的错误。即使我没有做任何循环。问题实际上是ProtectedRoute函数无法捕获参数。我尝试了console.log(),只得到了react上下文的状态。像App.js这样的路径和组件不会抛出任何道具这是我在控制台时的道具内容。log
isLoggedIn:true login:cridentials=>{…}logout:()=>{…}token:“myJWTtoken”用户:{myUserInfo}
您能提供一个工作的JSFIDLE吗?weedoze的第一条评论应该适合您。