渴望成为大牛的男人

渴望成为大牛的男人

路由进阶

比如这样: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>
                    )
                }
            }
总之,万变不离其宗,都是一样的道理
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就是我们当前这个路由的路径,有了这个,不管路由嵌套层次有多深,我们都可以通过这种方式来写上一级的路由
还可以通过/foodList?id=6这种方式传参,传过去的值在props中的location里面的的search中
-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>
//使用自定义的组件:
<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里面就有路由信息了
11-20 06:14