React路由-进阶篇

路由进阶

1.多级路由,和之前的思想一样,在子路由里面继续写Route,继续挂载组件,就可以实现多级路由

比如这样:class Food extends Component{
                render() {
                    return (
                        <Fragment>
                            <Link to="/food/foodlist">foodlist</Link>
                            &nbsp;
                            <Link to="/food/foodmenu">foodmenu</Link>
                            <Switch>
                                <Route path="/food/foodlist" component={FoodList}>foodlist</Route>
                                <Route path="/food/foodmenu" component={FoodMenu}>foodmenu</Route>
                            </Switch>
                        </Fragment>
                    )
                }
            }
总之,万变不离其宗,都是一样的道理

2.假如说多级路由嵌套层次太深,那我们写子级路由的path就会特别麻烦,所以我们不妨这样搞

const Food = ({match}) => {
  return (
    <div>
      <Link to={`${match.path}/foodmenu`}>foodmenu</Link>
      <Switch>
        <Route path={`${match.path}/foodmenu`} component={FoodMenu}/>
      </Switch>
    </div>
  )
}
//在这里,match是从props解构出来的,如果你不嫌麻烦,大可以写成this.props.match,match.path就是我们当前这个路由的路径,有了这个,不管路由嵌套层次有多深,我们都可以通过这种方式来写上一级的路由

2.动态路由传参/foodList/:id,传过去的值就在路由挂载组件的props中,props里面有个match,match中有个params,都在这里面,要注意:props只有在路由挂载的组件中才有

还可以通过/foodList?id=6这种方式传参,传过去的值在props中的location里面的的search中

3.编程式导航,可以在一个组件中用this.props.history.push("/path",{name:"hellow"}),来进行传参,传过去的值在props.location.state中
4.Route里面还有两个属性,render和children

-render是一个函数,语法:render={()=>{return <div></div>}},只要你的路由匹配了,这个函数才会执行
-children也是一个函数,不管匹配不匹配,这个函数都会执行
-他们两个有个优先级关系,render的优先级总是高于children,是会覆盖children的
 <Fragment>
    <h1>header</h1>
    <Link to="/wiki/wikiList/">gogogo</Link>
    <Route
        path="/wiki/wikiList"
        render={
            ()=>{
                return <div>wikilist-children</div>
            }
        } //这个是只有当你路由匹配到了/wiki/wikiList才会执行
        // children={() => {
        //     return <div>wikilist-children</div>
        //   }
        // }    //这个是只要你的路由跳到wiki了,那children就会执行
    >    
    </Route>
</Fragment>

5.withRouter,一个典型的高阶组件,如果我们既想实现点击跳转,又不想用Link的那个a标签,我们可以使用withRouter给我们吐出来一个实现点击跳转路由的组件,代码例子:

//使用自定义的组件:
<CustomNavLink to="/food">food</CustomNavLink>
<CustomNavLink to="/wiki">wiki</CustomNavLink>
<CustomNavLink to="/profile">profile</CustomNavLink>
//给自定义组件实现点击功能:
const CustomNavLink = withRouter(class EnhenceCustomNavLink extends Component {
    render () {
      return (
        <li onClick={this.goto.bind(this)}>
          {
            this.props.location.pathname === this.props.to ? '>' + this.props.children : this.props.children
          }
        </li>
      )
    }
    goto () {
      this.props.history.push(this.props.to)
    }
})

//加入你的组件没有路由信息,你可以使用withRouter(component)这样将这个组件包起来,props里面就有路由信息了
原文地址:https://www.cnblogs.com/bai1218/p/9985552.html