React-Router

使用方法

import { HashRouter, BrowserRouter, Link, NavLink, Redirect, Switch, Route } from 'react-router-dom'
class App extends React.Component {
  render() {
    return (
      <HashRouter>
        {/* 重定向 */}
        <Redirect from="/" to="/user"></Redirect>
        {/* 加上 exact 严格匹配 */}
        <NavLink exact to='/' activeClassName="active">去Home</NavLink>
        {/* activeClassName 设置高亮所使用的类名, activeStyle 自定义样式 */}
        <NavLink to='/user' activeStyle={{ color: 'green' }}>去User</NavLink>
        {/* props.match.params.id  */}
        <Link to={{ pathname: '/user/1' }}></Link>
        {/* props.location.hh.msg  官方使用 state 实际任何属性都可以 */}
        <Link to={{ pathname: '/home', hh: { msg: 'hh' } }}></Link>
        {/* props.location.search */}
        <Link to={{ pathname: '/home', search: '?name=gg' }}></Link>
        {/* props.location.hash */}
        <Link to={{ pathname: '/home', hash: '#hh' }}></Link>
        {/* 获取 ?name=meow 参数方法原生 JS const params = new URLSearchParams(props.location.search); params.get('name') */}

        {/* 可以不使用 Swtich 包裹,实现严格匹配 */}
        <Route strict exact path='/' > // 
          <Home />
        </Route>
        <Switch>
          <Route exact path='/' component={Main}></Route>
          <Route path="/home">
            <Home></Home>
          </Route>
          {/* ?表示可以有可无  */}
          <Route path="/user/:id?/:pid?" component={Home}></Route>
          <Route path='/cart' render={(props) => <Home {...props} />}>
          </Route>
        </Switch>
      </HashRouter>
    )
  }
}

编程式导航

this.props.history.push('/', {msg: 'hh'}) // 跳转页面 this.props.location.state.msg
this.props.history.replace()
this.props.history.go()
this.props.history.goForward()
this.props.history.goBack()

withRouter

子组件没有直接被路由管理,无法获取到路由对象

import {withRouter} from 'react-router-dom' 
export default withRouter(Child)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。