react 05 router
Posted fanlinaweb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react 05 router相关的知识,希望对你有一定的参考价值。
安装
npm i react-router-dom -- save
<Router basename="/admin">
<Route path="/" exact component={()=>{<div>首页</div>}}>
<Route path="/about" exact component={()=>{<div>关于</div>}}>
</Router>
重定向组件
Redirect
import React from ‘react‘; import ‘./App.css‘; import { BrowserRouter as Router, Route, Link, Redirect } from ‘react-router-dom‘ function LoginInfo(props) { console.log(props) // 这是通过 state 传参 if(props.location.state.loginState === ‘success‘) { return ( <Redirect to="/admin"></Redirect> ) }else { return ( <Redirect to="/login"></Redirect> ) } } let login = ()=>{ let obj = { pathname:‘/logininfo‘, state:{ loginState:‘success‘ } } return ( <div> <Link to={obj} >登录</Link> </div> ) } class App extends React.Component{ render(){ return ( <Router> <Route path="/" exact component={()=>(<div>首页</div>)}></Route> <Route path="/login" exact component={()=>(<div> <Link to="/logininfo?loginState=‘success‘" >登录</Link> </div>)}></Route> <Route path="/login" exact component={login}></Route> <Route path="/logininfo" exact component={LoginInfo}></Route> </Router> ) } } export default App;
switch 内部的Route 只匹配一次
class App extends React.Component{ render(){ return ( <Router> <Switch> <Route path="/" exact component={()=>(<div>首页</div>)}></Route> <Route path="/login" exact component={()=>(<div> <Link to="/logininfo?loginState=‘success‘" >登录</Link> </div>)}></Route> <Route path="/login" exact component={login}></Route> <Route path="/logininfo" exact component={LoginInfo}></Route> <Route path="/abc" exact component={()=>(<div>首页1</div>)}></Route> <Route path="/abc" exact component={()=>(<div>首页2</div>)}></Route> </Switch> </Router> ) } }
不使用Link 按钮直接跳转
class ChildCom extends React.Component { render() { return ( <button onClick={this.show}> 点击回首页 </button> ) } show=()=>{ // console.log(this.props); this.props.history.push("/",{msg:‘给首页的数据‘}) } } class App extends React.Component{ render(){ return ( <Router> <Route path="/" exact component={(props)=>{console.log(props);return(<div>首页</div>)}}></Route> </Switch> </Router> ) } }
以上是关于react 05 router的主要内容,如果未能解决你的问题,请参考以下文章
react-router-relay 是不是与 Relay 模式不一致?
react-router如何从客户端向服务器中间件发送请求?
如何在 django 项目中使用 react-router 处理 404 错误