withRouter使用
import React from 'react'; import {Switch,NavLink,Route,Redirect,withRouter} from 'react-router-dom'; import Detail from './Detail'; import Login from './Login' import User from './User'; import MyRoute from './MyRoute' class Header extends React.Component{ constructor(props){ super(props); } render(){ return( <div> <NavLink to='/login'>我是登录页</NavLink> <br/> <NavLink to="/detail/1">我是分页一</NavLink> <br/> <NavLink to="/user">我是用户页</NavLink> <br/> <Switch> <Redirect from='/' to="/login" exact /> <Route path='/login' component={Login}/>
//权限路由 使用 <Route path='/detail/:id?' render={ (props)=>{ return sessionStorage.getItem('user')? <Route component={Detail} {...props}/>:<Redirect to='/login'/> } }/>
//权限路由使用 <Route path='/user' render={ (props)=>{ return sessionStorage.getItem('user')? <Route component={User} {...props}/>:<Redirect to='/login'/> } }/> </Switch> </div> ) } } export default withRouter(Header);
这样使用很麻烦,所以封装组件进行复用
import React from 'react'; import {Route,Redirect} from 'react-router-dom'; class MyRoute extends React.Component{ constructor(props){ super(props); } render() { console.log(this.props)
//利用组件传值的特性封装成组件利用组件进行封装 let {path,component:Com} = this.props; return ( <Route path={path} render={ (props)=>{ return sessionStorage.getItem('user') ? <Com {...props}/> :<Redirect to="/login" /> } }/> ) } } export default MyRoute;
login.js
import React from 'react'; class Detail extends React.Component{ constructor(props){ super(props); this.login = this.login.bind(this); console.log(this.props); }; login(){ let username = this.node.value; if(username==='admin'){ sessionStorage.setItem('user','admin'); } this.props.history.push('/user')
//编程式导航类似vue 在使用withRouter以后 }; render(){ return ( <div>
//简易的写法 <input type="text" ref={node=>this.node=node}/> <button onClick={this.login}>登录</button> </div> ) } } export default Detail;
user.js
import React from 'react'; class User extends React.Component{ quit(){ sessionStorage.clear();
//清除session并导航到登录页面 this.props.history.push('/login'); } render() { console.log(this.props); return ( <div> <input type="button" value="退出" onClick={this.quit.bind(this)}/> </div> ) } }; export default User;
这是简化demo以后的代码
import React from 'react'; import {Switch,NavLink,Route,Redirect,withRouter} from 'react-router-dom'; import Detail from './Detail'; import Login from './Login' import User from './User'; import MyRoute from './MyRoute' class Header extends React.Component{ constructor(props){ super(props); } render(){ return( <div> <NavLink to='/login'>我是登录页</NavLink> <br/> <NavLink to="/detail/1">我是分页一</NavLink> <br/> <NavLink to="/user">我是用户页</NavLink> <br/> <Switch> <Redirect from='/' to="/login" exact /> <Route path='/login' component={Login}/>
//使用了封装的组件 该组件利用组件传值的特性 <MyRoute path='/detail/:id?' component={Detail} /> <MyRoute path='/user' component={User}/> </Switch> </div> ) } } export default withRouter(Header);