我有一个基本组件,它通过API检查身份验证。如果身份验证失败,我的脚本将无法显示UI,但它不像我期望的那样重定向。
class Base extends Component {
constructor(props) {
super(props);
this.state = {
isAuth: false,
isLoaded: false
};
}
componentDidMount() {
axios.post(process.env.REACT_APP_API_URL+'/account/validate-session', {
session_id: cookies.get('session_id'),
account_id: cookies.get('account_id')
})
.then(function (response) {
if(response.data.status === "OK"){
this.setState({
isAuth: true,
isLoaded: true
})
}
}.bind(this))
.catch(function (error) {
this.setState({
isAuth: false,
isLoaded: true
})
}.bind(this));
}
componentWillMount(){
this.currentPage = [
this.props.page
]
}
render() {
let date = new Date().getFullYear();
if(this.state.isLoaded) {
return (
this.state.isAuth ?
<Layout className="layout">
<Header className="header">
<div className="logo" />
<div className="title">
{/*{this.props.title}*/}
Homepage
</div>
<Menu theme="dark" mode="horizontal" defaultSelectedKeys={this.currentPage} style={{ lineHeight: '64px', float: 'left', marginLeft: '300px'}}>
<Menu.Item key="/home">
<Link className="nav-text" to="/home">Home</Link>
</Menu.Item>
<Menu.Item key="/upload">
<Link className="nav-text" to="/upload">Upload</Link>
</Menu.Item>
</Menu>
<Menu theme="dark" mode="horizontal" defaultSelectedKeys={this.currentPage} style={{ lineHeight: '64px', float: 'right'}}>
<Menu.Item key="/logout">
<Link className="nav-text" to="/logout">Logout</Link>
</Menu.Item>
</Menu>
</Header>
<Content style={{ padding: '0 50px' }}>
{/*<Breadcrumb style={{ margin: '12px 0' }}>
<Breadcrumb.Item>Home</Breadcrumb.Item>
<Breadcrumb.Item>{this.currentPage}</Breadcrumb.Item>
</Breadcrumb>*/}
<div style={{ padding: 24, background: '#fff' }}>
{this.props.children}
</div>
</Content>
<Footer style={{ textAlign: 'center' }}>
Copyright {date} Company, Inc.
</Footer>
</Layout>
:
<Redirect to="/"/>
);
} else {
return null;
}
}
}
路由器:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (
<Component {...props}/>
)}/>
)
ReactDOM.render((
<LocaleProvider locale={enUS}>
<Router>
<Switch>
<Route exact path="/" component={Login}/>
<PrivateRoute exact path="/home" component={Home} />
<PrivateRoute exact path="/upload" component={Upload}/>
<PrivateRoute exact path="/logout" component={Logout}/>
<PrivateRoute exact path="/review/:uploadId" component={Review}/>
<Route component={ NotFound } />
</Switch>
</Router>
</LocaleProvider>
), document.getElementById('root'))
registerServiceWorker();
我可以看到正在进行的API调用,我可以看到它返回401验证失败。用户界面显示空白页面,但重定向不起作用。
有什么想法吗?