Redirect
- 资源重定向, 也就是可以在访问某个资源地址的时候重定向到另外一个资源地址
- 例如: 访问 /user 重定向到 /login
假如说我现在需要实现这么一个功能就是当用户登陆过了之后访问 /user 时就显示用户相关的组件信息,否则跳到登录界面进行登录才可访问。
新建 User.js:
import React from 'react';
import {Redirect} from 'react-router-dom';
class User extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
isLogin: false
}
}
render() {
const user = (
<div>
<h1>用户界面</h1>
<p>用户名: BNTang</p>
<p>密码: 666666</p>
</div>
);
const login = <Redirect to={'/login'}/>
return this.state.isLogin ? user : login;
}
}
export default User;
新建 Login.js:
import React from 'react';
class Login extends React.PureComponent {
render() {
return (
<div>Login</div>
)
}
}
export default Login;
更改 App.js:
import React from 'react';
import Home from './components/Home'
import About from './components/About'
import User from './components/User';
import Login from './components/Login';
import Other from './components/Other';
import {BrowserRouter, Link, Route, Switch} from 'react-router-dom';
class App extends React.PureComponent {
render() {
return (
<div>
<BrowserRouter>
<Link to={'/home'}>Home</Link>
<Link to={'/home/about'}>About</Link>
<Link to={'/user'}>User</Link>
<Switch>
<Route exact path={'/home'} component={Home}/>
<Route exact path={'/home/about'} component={About}/>
<Route exact path={'/user'} component={User}/>
<Route exact path={'/login'} component={Login}/>
<Route component={Other}/>
</Switch>
</BrowserRouter>
</div>
)
}
}
export default App;