美文网首页
react-router的使用

react-router的使用

作者: Jason_SheYing | 来源:发表于2019-03-28 08:46 被阅读0次

    react-router的使用

    下载依赖

        npm i react-router-dom --save-dev
    

    引入

        import { BrowserRouter } from 'react-router-dom'
    

    HashRouter的用法

    注意: 重复点击的时候会报路径重复的警告
        <Route path="/home" component={Home}/>
        <Route path="/about" component={About}/>
        ReactDOM.render(
          <HashRouter>
            <App />
          </HashRouter>
          , document.getElementById('root')
        );
    

    Link的使用

    代替a标签

        <Link to="/home">主页</Link>
    

    BrowserRouter的用法(推荐)

        <li><Link to="/home">主页</Link></li>
        <li><Link to="/about">关于我们</Link></li>
        <Route path="/home" component={Home}/>
        <Route path="/about" component={About}/>
        ReactDOM.render(
          <BrowserRouter>
            <App />
          </BrowserRouter>
          , document.getElementById('root')
        );
    

    Switch的使用

    Switch只会匹配一个子路由
        <Switch>
          <Route exact path="/" component={Home}></Route>
          <Route path="/about" component={About}></Route>
        </Switch>
    
    exact表示精确匹配,建议加上

    Redirect的使用

        <Switch>
          <Route exact path="/home" component={Home}></Route>
          <Route path="/about" component={About}></Route>
          <Redirect from="/" to="/home" />
          <Route component={ NotFound } />
        </Switch>
    
    注意: Redirect需放在Switch的最后一项,若需提供404页面,则需注释掉Redirect

    相关文章

      网友评论

          本文标题:react-router的使用

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