当用户未登录时,我如何防止React路由被调用?
想要在调用 / 时显示一个带有登录表单的单页面。
只有在用户已登录的情况下才能调用其他每个路由。
谢谢。
index.js
const render = () => {
ReactDOM.render(
<Provider store={store}>
<AppContainer>
<Router history={createHistory}>
<div>
<div className={t.topBar}>
<TopBarHelper/>
</div>
<div className={css.sidebararound}>
</div>
<Route exact path="/" component={Login}/>
<PrivateRoute path="/dashboard" component={Dashboard}/>
....
const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {
this.isAuthenticated = true
setTimeout(cb, 100) // fake async
},
signout(cb) {
this.isAuthenticated = false
setTimeout(cb, 100)
}
}
const AuthButton = withRouter(({ history }) => (
fakeAuth.isAuthenticated ? (
<p>Welcome!</p>
) : (
<p>You are not logged in.</p>
)
))
登录代码在一个单独的文件中,代码如下:
class Login extends Component {
constructor(props) {
super(props);
this.changeHandler = this.changeHandler.bind(this);
this.state = {
activeSnackbar: false,
snackbarText: '',
redirectToReferrer: false
};
}
componentDidMount() {
this.getData()
};
/**
* Fetches all Data needed for this view
*/
getData() {
console.log(this.props)
};
/**
* Handle Change
* @param field
* @param value
*/
changeHandler(value, {target: {name, type}}) {
this.setState({
[name]: type === 'number' ? parseInt(value, 10) : value,
});
}
/**
* Submit new Ticket Form
* @param event
*/
handleLogin = (event) => {
this.context.router.push('/dashboard');
// axios.post(API_URL + '/dashboard')
// .then((response) => {
// })
// .catch(function (error) {
// console.log(error);
// });
};
render() {
return (
<div>
<div className={css.loginpanel}>
<div className={css.loginpanellogo}>
<img src={logo} width="200px"/>
</div>
<div className={css.loginpanelform}>
<h1><T value="user.login.welcome"/></h1>
<form id="login" method="POST" action="">
<Input type='email' label={<T value='user.login.email'/>} name='email' value={this.state.email} onChange={this.changeHandler}/>
<Input type='password' label={<T value='user.login.password'/>} name='password' value={this.state.password} onChange={this.changeHandler}/>
<br />
<Button icon='save' onClick={this.AuthButton} label={<T value="user.login.signin"/>} raised primary/>
<Button label={<T value="user.login.signup"/>} raised/>
</form>
<br/>
</div>
</div>
</div>
);
}
}
export default connect()(Login);
但是我无法从登录页面调用AuthButton函数