Reactjs 受保护的路由发出从react路由器redux到已连接react路由器的切换
我正在将我的应用程序从Reactjs 受保护的路由发出从react路由器redux到已连接react路由器的切换,reactjs,redux,react-router-v4,connected-react-router,Reactjs,Redux,React Router V4,Connected React Router,我正在将我的应用程序从react router redux-迁移到-->连接的react router,但是,我发现了一个问题。目前,我有一些受保护的路由(需要经过身份验证的用户),例如仪表板 export default function Routes(props, context) { return ( <Switch> <Route exact path="/" component={Login} /> <Route pat
react router redux
-迁移到-->连接的react router
,但是,我发现了一个问题。目前,我有一些受保护的路由(需要经过身份验证的用户),例如仪表板
export default function Routes(props, context) {
return (
<Switch>
<Route exact path="/" component={Login} />
<Route path="/login" component={Login} />
<Route
render={props => <Authorization {...props} routes={AuthRoutes} />}
/>
</Switch>
)
}
const AuthRoutes = [
<Switch>
<Route path="/dashboard" component={Dashboard} />,
<Route component={Error404} />
</Switch>,
]
导出默认功能路由(道具、上下文){
返回(
}
/>
)
}
常数AuthRoutes=[
,
,
]
授权组件如下所示:
import React,{Component}来自“React”
从“react redux”导入{connect}
从“react router”导入{Redirect,withRouter}
类授权扩展组件{
未经验证(){
const{auth,app}=this.props
const{search}=app
console.log('============================================================================'))
console.log('Auth:',Auth)
console.log('============================================================================'))
if(身份验证和身份验证令牌){
返回此.props.routes.map((路线,索引)=>
cloneElement(路由,{key:index})
)
}否则{
返回
}
}
render(){
返回{this.isAuthenticated()}
}
}
导出默认连接(状态=>({
auth:state.auth,
app:state.app,
}))(带路由器(授权))
用户登录后,会将其定向到/dashboard
路径,并将令牌
保存到redux存储中的auth(保存到localStorage)
问题:
- 刷新第1页时,console.log语句(来自授权)
输出
并将用户重定向到Auth:{token:null}
/login
- 第二次刷新console.log语句时(来自授权)输出
该
和用户重定向到Auth:{token:}
(正确的行为)/dashboard
- 第三次刷新console.log语句时(来自授权)输出
该
和用户重定向到Auth:{token:null}
/login
- 第四次刷新console.log语句时(来自授权)输出
该
和用户重定向到Auth:{token:}
(正确的行为)/dashboard
授权组件都会在有时间从本地存储恢复之前访问身份验证状态
如果我恢复使用react router redux
,则在登录后的每个页面刷新时,用户都会被正确重定向到/dashboard
这件事你解决了吗?我也遇到过同样的问题,并注意到根据文档,路由器的位置非常重要。尝试用HoC和路由器
包装连接的组件<代码>使用路由器导出默认值(连接(…)(授权))
我会试试,它为您解决了问题吗?我的问题是,我无意中用路由器从反应路由器dom
将所有内容包装在连接外部
中。我对路由器的有不同的看法,有时它能工作,而另一些则不行。你有测试回购协议吗?我看看能不能看出什么事。
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Redirect, withRouter } from 'react-router'
class Authorization extends Component {
isAuthenticated() {
const { auth, app } = this.props
const { search } = app
console.log('====================================')
console.log('Auth:', auth)
console.log('====================================')
if (auth && auth.token) {
return this.props.routes.map((route, index) =>
React.cloneElement(route, { key: index })
)
} else {
return <Redirect to={{ pathname: '/login', search }} />
}
}
render() {
return <div style={{ width: '100%' }}>{this.isAuthenticated()}</div>
}
}
export default connect(state => ({
auth: state.auth,
app: state.app,
}))(withRouter(Authorization))