react进阶(三)——嵌套路由的使用

复习

上一张我们知道了react-router的基本使用,了解了switch、browserRouter、HashRouter等组件,还知道了this.props的参数,一般就是组件传递的数据和路径相关的对象,例如location、match、history,请牢牢记住这些属性,因为他们在以后很重要

嵌套路由怎么用?

这里我是用一个例子详细解释一哈,

import React, {Component} from 'react'
import {Switch, Route, Redirect} from 'react-router-dom'

import MyNavLink from '../app/MyNavLink'
import News from './news/News'
import Messages from './message/Message'

export default class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        const {path} = this.props.match;
        return (
            <React.Fragment>
                <div>Home组件内容</div>
                <div>
                    <ul className="nav nav-tabs">
                        <li>
                            <MyNavLink to={`${path}/news`} style={{marginRight:50,textDecoration:'none'}}>news</MyNavLink>
                        </li>
                        <li>
                            <MyNavLink to={`${path}/messages`} style={{textDecoration:'none'}}>messages</MyNavLink>
                        </li>
                    </ul>
                </div>
                    {/*在路由里面有两种方式向组件传值,如一下,props是当前的props,里面包含了history、location、match等
                        子组件接收还是使用this.props(有状态组件);如若不传props,子组件的props就只有extra
                    */}

                {/*
                    这里嵌套路由有两种书写方式:
                        第一种:父级组件的路由/当前的路由,例如父级的路由是/home,那么news的路由就是/home/news
                        第二种:当父级路由无参数,使用this.props.match.path/当前路由
                               当父级路径含有参数是使用this.props.location.pathname?search/当前路由
                        什么时候用第一种,什么时候用第二种呢?
                        第一种的使用情况我建议在父级路由层级不超过2层是使用,超过两层则使用第二种,使用第二种时注意父级路由有无参数
                    */}
                <Switch>
                    <Route path={`${path}/news`} component={props => <News {...props} extra={'someVariable'} />}/>
                    <Route path={`${path}/messages`} render={props => <Messages {...props} extra={'someVariable'} />}/>
                    <Redirect to={`${path}/news`}/>
                </Switch>
            </React.Fragment>
        );
    }
}

下一章进入redux。多谢支持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值