前言:
这个例子的难点在于他涉及到多个页面之间的公共数据(即全局变量),实际项目中会用redux管理全局变量,但是考虑到例子的理解难度,我这里采用了本地存储localStorage来管理数据。这样这个例子就好理解了很多。
实现效果:
实现思路:
这个项目里有一个变量是isLogin,判断用户是否登录,只有登录的用户才可以访问Protected Page,该变量是该程序的核心。
我们先来看一下App.js:
import AuthButton from '../components/AuthButton';
import Login from './login/Login';
import Public from './public/Public';
import Protected from './protected/Protected';
class PrivateRoute extends Component {
render () {
if (this.props.isLogin) {
return (
<Route path={this.props.path} component={Protected}/>
)
} else {
return (
<Redirect from={this.props.path} to="/login" />
)
}
}
}
class App extends Component {
constructor () {
super();
this.state = {
isLogin: false
}
}
componentDidMount () {
setInterval(() => {
this.setState({
isLogin: (localStorage.getItem('isLogin')) === 'true' ? true : false
})
}, 200)
}
render () {
return (
<Router>
<div>
<AuthButton isLogin={this.state.isLogin} />
<ul>
<li><Link to="/public">Public Page</Link></li>
<li><Link to="/protected">Protected Page</Link></li>
</ul>
<Switch>
<Route path="/public" component={Public}/>
<Route path="/login" component={Login} />
<PrivateRoute isLogin={this.state.isLogin} path="/protected"/>
</Switch>
</div>
</Router>
)
}
}
涉及到的知识点:
1、componentDidMount函数:组件挂载之后调用,全程只调用一次。因为isLogin的值会在其他页面被改变,为了实时获取isLogin当前的值,我们这里调用了setInterval函数。
2、Switch组件:只渲染第一个与当前访问地址匹配的<Route>或<Redirect>;
3、Redirect组件:重定向URL,页面由from对应的路径重定向到to对应的路径;
子组件Login.js:
export default class Login extends Component {
clickEvent() {
window.localStorage.setItem('isLogin', true);//console.log(this);
}
render() {
const {from} = this.props.location.state || { from: {pathname: '/'} }
return (
<div>
<p>You must log in to view the page at {from.pathname}</p>
<input type="button" value="Log in" onClick={()=>this.clickEvent()}/>
</div>
)
}
}
涉及到的知识点:
1、const {from} = this.props.location.state || { from: {pathname: '/'} },es6的对象解构赋值。
2、箭头函数出发事件,避免clickEvent中this指向的错误(虽然这里clickEvent并没有用到this)。
注销组件:
export default class AuthButton extends Component {
clickEvent() {
window.localStorage.setItem('isLogin', false);//console.log(this)
}
render () {
return (
<div>
{this.props.isLogin ? <p>Welcome!<button onClick={this.clickEvent}>Sign out</button></p> : <p>You are not logged in.</p>}
</div>
)
}
}
我这里提到注销组件主要想引出react中方法调用时this问题。细心的同学可能会发现注销组件中触发点击事件用的是onClick={this.clickEvent},但是登录组件中则是onClick={() => this.clickEvent()};这两个有什么区别呢?
咱们这里的例子比较简单没有用到this,倘若你在两个clickEvent方法中打印this,注销中的this为undefined;登录中的this为Login,这是因为类中的方法默认是不会绑定this的,但是利用箭头函数(箭头函数的this和定义时有关和调用无关)和bind方法(可以改变函数中this的指向)可以改变this的指向。
倘若你还不理解请参考我的github上的这个示例:https://github.com/guoqin721/react-router-dom3