美文网首页
react-router

react-router

作者: 海豚先生的博客 | 来源:发表于2020-05-15 18:49 被阅读0次

react-router-dom

  • BrowserRouter (H5的history模式,不刷新改变地址栏)
    包裹根组件App
    刷新会向服务器请求该地址资源,需要服务器配合
  • HashRouter
    刷新不会请求服务器
  • MemoryRouter 存在内存中
    地址栏不会改变,刷新回到首页
    react-native可以用

路由传参

// 传递
<Route path="/course/:id" >
<Link to="/course/10" >
// 获取
let { id } = this.props.match.params
URL的查询字符串/foo?bar=baz,可以用this.props.location.query.bar获取。

嵌套路由

// 嵌套route
import { createBrowserHistory } from "history";
<Router history={hashHistory}>
  <Route path="/" component={App}>
    <Route path="/repos" component={Repos}/>
    <Route path="/about" component={About}/>
    <Route path="/about" ><About /></Route>
  </Route>
</Router>
let { path } = this.props.match
// 保存当前path,避免path更换后,手动改低层级的路由名称
<Route path={`${path}/js`} > </Route>
// 获取后端路由层级进行渲染,省略map函数包裹
<Link to={ `${path}/${course.ID}` } >{course.title}</Link>
// 使用render时,props丢失,但render有默认参数props
<Route path={ `${path}/${course.ID}` } render={ (props) => (
   // 使用work组件本身,work中嵌套work组件
   <Work {...props} data = {course.children} />
)}
</Route>

路由跳转、传参

<Link to={
  { 
    pathname: '/work',
    search: '?a=12',
    hash:'#11'
  }
} />
<Redirect to='/login' />
this.props.history.push('/work') ({pathname:xxxxx,xxx:xxx})
match获取不到search,history可以
import { useParams } from "react-router-dom";
<Route path="/:id" children={<Child />} >
child中 let { id } = useParams()
// 原生的api
let params = new URLSearchParams(location.seatch)
params.get('a') //12

路由改变、history.push(),都会触发componentDidUpdate(),

路由钩子

用来做登录认证

onLeave/onEnter
routerWillLeave 组件钩子

onEnter与onChange

onEnter 触发时机是 is about to be entered,当路由进入即触发。
onChange 触发时机是 the location changes,监听的是子路由。
从'/'页面中跳转到login,触发onEnter,从'/info'页面中跳转到login,触发onChange。

<Route
    path="messages/:id"
    onEnter={
      ({params}, replace) => replace(`/messages/${params.id}`)
    } 
 />

IndexRoute 与IndexRedirect

IndexRoute指定一个路由的默认页。而 IndexRedirect 指定一个路由地址作为跳转地址

相关文章

网友评论

      本文标题:react-router

      本文链接:https://www.haomeiwen.com/subject/bolhohtx.html