我有以下路由配置:
return (<div>
<Router>
<div>
<Route path='/login' component={LoginPage}/>
<EnsureLoggedInContainer>
<Route path='/abc' component={abc} />
</EnsureLoggedInContainer>
</div>
</Router>
</div>
);
EnsureLoggedInContainer是:
import React from 'react';
import { connect } from "react-redux";
class EnsureLoggedInContainer extends React.Component
{
componentDidMount() {
if ( !this.props.isLoggedIn )
{
// this.props.history.push('/login');
this.context.router.push('/contact');
}
}
render() {
// console.log(this.props);
if ( this.props.isLoggedIn )
{
return this.props.children;
}
else
{
return null;
}
}
}
const mapStateToProps = (state,ownProps) => {
return{
isLoggedIn : state.isLoggedIn,
// currentURL : this.props
}
}
export default connect(mapStateToProps)(EnsureLoggedInContainer);
但是,历史推动:this.props.history.push('/login');
无效。这里的历史不存在。
如果我使用这样的配置:
<Route component={EnsureLoggedInContainer}>
<Route path='/myjs' component={MyjsPage} />
</Route>
我遇到的问题如下:
Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored
reactjs中最好的身份验证方式是什么?
答案 0 :(得分:1)
从我所看到的React路由器设计中,您似乎使用的是React路由器版本4
在这种情况下,您可以在Component Itself中指定路由,并使用withRouter进行动态重定向,如
return (<div>
<Router>
<div>
<Route path='/login' component={LoginPage}/>
<EnsureLoggedInContainer/>
</div>
</Router>
</div>
);
和
import React from 'react';
import { connect } from "react-redux";
import {withRouter} from "react-router";
class EnsureLoggedInContainer extends React.Component
{
componentDidMount() {
if ( !this.props.isLoggedIn )
{
this.props.history.push('/login');
}
}
render() {
// console.log(this.props);
if ( this.props.isLoggedIn )
{
return <Route path='/abc' component={abc} />
}
else
{
return null;
}
}
}
const mapStateToProps = (state,ownProps) => {
return{
isLoggedIn : state.isLoggedIn,
// currentURL : this.props
}
}
export default connect(mapStateToProps)(withRouter(EnsureLoggedInContainer));