精华内容
下载资源
问答
  • react-router

    2017-08-07 22:48:13
    react-router 实例
  • React-Router

    2020-12-22 10:16:00
    React-Router 最新的路由的版本是5.2的版本。里面的话提供了一些包 所在在做web端开发的时候只需要安装react-router-dom就可以了,因为内部已经包含了最核心的内容了。 react-router | react-router-native | react-...

    React-Router

    最新的路由的版本是5.2的版本。里面的话提供了一些包

    所在在做web端开发的时候只需要安装react-router-dom就可以了,因为内部已经包含了最核心的内容了。

    react-router | react-router-native | react-router-config

    路由的简单使用

    ​ 安装路由: yarn add react-router-dom

    ​ 需要在最外层的节点上面:(hash vs history)

    index.js

    import {HashRouter as Router} from "react-router-dom"
    ReactDOM.render(
      <Router>
        <App />
      </Router>,
      document.getElementById('root')
    );

    ​ 使用Route实现路由

    App.js

    import React,{Component} from 'react';
    import {Route,Redirect,Switch} from "react-router-dom"
    import Home from "./views/Home"
    import Article from "./views/Article"
    import NotFound from "./views/NotFound"
    //Route指代路由对象,path匹配路径,component代表路由组件  exact就是将地址栏与path必须完全一致
    //Redirect重定向 to跳到指明的路径
    //Switch 内部的路由只要匹配一个就结束了,下面的就不匹配了
    class App extends Component{
      render(){
        return (
          <Switch>
            <Route path="/home" component={Home}/>
            <Route path="/article" component={Article}/>
            <Route path="/404" component={NotFound}/>
            <Redirect to="/home" from="/" exact/>   
            <Redirect to="/404"/>
          </Switch>
        )
      }
    }
    export default App;

    声明式导航 (vue中router-link实现的)

    可以通过NavLink实现a标签的切换效果,渲染成a标签,并且带有active的class样式

    App.js

    import {Route,Redirect,Switch,NavLink as Link} from "react-router-dom"
    
    <Link to="/home" activeStyle={{color:'red'}}>首页</Link>
    <Link to="/article" activeStyle={{color:'red'}}>文章</Link>

    二级路由与动态跳转

    二级路由:

    Article文件:

    import React, { Component } from 'react'
    import {Route,NavLink as Link} from "react-router-dom"
    import ArticleDetail from './ArticleDetail';
    export default class Article extends Component {
        render() {
            return (
                <div>
                    <Link to="/article/1">文章一</Link>
                    <Link to="/article/2">文章二</Link>
                    <Route path="/article/:id" component={ArticleDetail}/>
                </div>
            )
        }
    }

    ArticleDetail中获取动态参数?

    因为ArticleDetail被Route进行包裹,就是路由组件了。它的属性上面就会有路由相关的api

    ArticleDetail.js

    import React, { Component } from 'react'
    export default class ArticleDetail extends Component {
        render() {
            //history/location/match的路由api了。
            return (
                <div>
                    文章详情 -- {this.props.match.params.id}
                </div>
            )
        }
    }

    路由常用的api方法

    Route中的render函数

    ​ 一旦通过Route组件的component属性指明的组件,那么这个路由组件上面就会有路由相关的api

    ​ (location / history / match)

    ​ 如果必须要传入额外属性的话,单纯使用component是解决不了的。

    <Route path="/home" render={(routeProps)=>{
    	return this.state.isLogin ? <Home {...routeProps} a={1}/> : "未登录"
    }}/>

    link的参数传递

    ​ 1.可以通过动态路由的方式进行参数传递

    ​ path="/article/:id"

    ​ Detail组件内部可以通过 this.props.match.params.id可以获取到动态参数

    ​ 2.可以通过query进行传参

    ​ path="/article?title=文章一"

    ​ Detail组件内部可以通过 this.props.location.search可以获取到 “?title=文章一”

    ​ 3.可以通过state进行隐式传参

    ​ to={{pathname:'/article/2',state:{title:'文章2'}}}

    ​ Detail组件内部可以通过 this.props.location.state.title可以获取到

    withRouter

    我们可以通过引入高阶组件withRouter,将普通组件进行包裹,那么BackHome就变成了伪路由组件,它本身不能实现跳转,但是仍然可以通过属性去访问到路由相关的api了。

    import React, { Component } from 'react'
    import {withRouter} from "react-router-dom"z
    // 如果封装BackHome组件调用的话,他上面是没有this.props.history属性的
    // 但是通过HOC withRouter包裹之后,这个BackHome就变成了一个伪路由组件,
    // 本身是不会跳转进来,只不过属性上面却有了路由相关的api。
    @withRouter
    class BackHome extends Component {
        back = ()=>{
            //通过编程式导航方式返回首页
            this.props.history.push("/home")
        }
    
        render() {
            return (
                <div>
                    <button onClick={this.back}>返回home</button>
                </div>
            )
        }
    }
    export default BackHome
    展开全文
  • React-router

    2020-06-04 15:38:53
    React-router react-router链接 实例链接 React-router安装 方式1: npx create-react-app demo-app cd demo-app npm install react-router-dom npm start 方式2:<script src=...

    React-router

    react-router链接
    实例链接

    React-router安装

    方式1:
    npx create-react-app demo-app
    cd demo-app
    npm install react-router-dom
    npm start
    方式2:<script src="https://unpkg.com/react-router/umd/react-router.min.js"></script>

    安装create-react-app并创建一个新项目。

    基础路由

    import React from "react";
    import {
      BrowserRouter as Router,
      Switch,
      Route,
      Link
    } from "react-router-dom";
    
    export default function App() {
      return (
        <Router>
          <div>
            <nav>
              <ul>
                <li>
                  <Link to="/">Home</Link>
                </li>
                <li>
                  <Link to="/about">About</Link>
                </li>
                <li>
                  <Link to="/users">Users</Link>
                </li>
              </ul>
            </nav>
    
            {/* <Switch>通过其子<Route> s查找呈现与当前URL匹配的第一个 */}
            <Switch>
              <Route path="/about">
                <About />
              </Route>
              <Route path="/users">
                <Users />
              </Route>
              <Route path="/">
                <Home />
              </Route>
            </Switch>
          </div>
        </Router>
      );
    }
    
    function Home() {
      return <h2>Home</h2>;
    }
    
    function About() {
      return <h2>About</h2>;
    }
    
    function Users() {
      return <h2>Users</h2>;
    }
    

    嵌套路由

    import React from "react";
    import {
      BrowserRouter as Router,
      Switch,
      Route,
      Link,
      useRouteMatch,
      useParams
    } from "react-router-dom";
    
    export default function App() {
      return (
        <Router>
          <div>
            <ul>
              <li>
                <Link to="/">Home</Link>
              </li>
              <li>
                <Link to="/about">About</Link>
              </li>
              <li>
                <Link to="/topics">Topics</Link>
              </li>
            </ul>
    
            <Switch>
              <Route path="/about">
                <About />
              </Route>
              <Route path="/topics">
                <Topics />
              </Route>
              <Route path="/">
                <Home />
              </Route>
            </Switch>
          </div>
        </Router>
      );
    }
    
    function Home() {
      return <h2>Home</h2>;
    }
    
    function About() {
      return <h2>About</h2>;
    }
    
    function Topics() {
      let match = useRouteMatch();
    
      return (
        <div>
          <h2>Topics</h2>
    
          <ul>
            <li>
              <Link to={`${match.url}/components`}>Components</Link>
            </li>
            <li>
              <Link to={`${match.url}/props-v-state`}>
                Props v. State
              </Link>
            </li>
          </ul>
    
          {/* 主题页面有自己的<Switch>,其中包含更多路线建立在/ topics URL路径上的文件。 你可以想到第二个<Route>作为所有主题的“索引”页面,或者没有选择主题时显示的页面 */}
          <Switch>
            <Route path={`${match.path}/:topicId`}>
              <Topic />
            </Route>
            <Route path={match.path}>
              <h3>Please select a topic.</h3>
            </Route>
          </Switch>
        </div>
      );
    }
    
    function Topic() {
      let { topicId } = useParams();
      return <h3>Requested topic ID: {topicId}</h3>;
    }
    

    React Router中的组件主要分为三类:
    路由器,像<BrowserRouter><HashRouter>
    路线匹配器,例如<Route><Switch>
    导航,像<Link><NavLink><Redirect>

    TodoList脚手架实例

    npx create-react-app demo-app
    cd demo-app

    公共npm注册表中安装React Router:
    npm install react-router-dom

    安装node-sass
    npm install node-sass

    ant组件库地址:
    http://ant.design/
    导入:npm install antd --save
    (如果网络环境不佳,推荐使用 cnpm)

    2.yarn安装:
    $ yarn create react-app antd-demo
    或 $ npx create-react-app antd-demo

    进入项目并启动
    $ cd antd-demo
    $ yarn start

    从 yarn 或 npm 安装并引入 antd。
    $ yarn add antd

    程序入口:index.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from './App';
    import * as serviceWorker from './serviceWorker';
    
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById('root')
    );
    
    serviceWorker.unregister();
    
    

    组件 APP.js

    import React from 'react';
    import './App.scss';
    
    // function App() {
    //   return (
    //     <div className="App">
    //       <h1>欢迎学习react</h1>  
    //       <h1>Hello,World</h1>
    //       <input type="text" onChange={}/>  
    //     </div>
    //   );
    // }
    
    class App extends React.Component{
      state = {
        val: '',
        list: []
      }
      handleChange = (event)=>{
        let val = event.target.value;
        this.setState({
          val
        })
      }
      handleAdd = ()=>{
        let {val,list} = this.state;
        list.push(val);
        this.setState({
          list
        })
      }
      render(){
        const {val,list} = this.state;
        const ListItem = list.map((item,index)=>{
          return <li key="index">{item}</li>
        });
        return <div>
          <h1>欢迎学习react</h1>  
          <h1>Hello,World</h1>
          <input type="text"  value={val} onChange={this.handleChange} />
          <button onClick={this.handleAdd}>添加</button>
          <ul>
            {ListItem}
          </ul>
        </div>
      }
    }
    
    export default App;
    
    

    App.sass

    div {
      text-align: center;
      font-size: 32px;
      h1{
        color: red;
        font-size: 30px;
      }
    }
    

    路由基本配置

    1.BrowserRouter/HashRouter

    1.用BrowserRouter
    入口文件index.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import Router from './router';
    import * as serviceWorker from './serviceWorker';
    
    ReactDOM.render(
      <React.StrictMode>
        <Router />
      </React.StrictMode>,
      document.getElementById('root')
    );
    
    serviceWorker.unregister();
    

    Router.js

    import React from 'react';
    import {BrowserRouter as Router, Route} from 'react-router-dom'
    import App from './pages/app'
    import Login from './pages/login'
    import Home from './pages/home'
    
    export default function IRouter(){
        return <Router>
            <Route path="/" component={App}></Route>
            <Route path="/login" component={Login}></Route>
            <Route path="/home" component={Home}></Route>
        </Router>
    }
    

    三个子页面
    app.js

    import React from 'react'
    
    export default function App(){
        return <div>This is App</div>
    }
    

    login.js

    import React from 'react'
    
    export default function Login(){
        return <div>This is Login</div>
    }
    

    home.js

    import React from 'react'
    
    export default function Home(){
        return <div>This is Home</div>
    }
    

    通过http://localhost:3000/home访问时,会出现
    This is App
    This is Home
    (只要匹配都显示)

    2.用HashRouter

    import {HashRouter as Router, Route, Switch} from 'react-router-dom'
    

    访问路径变为 http://localhost:3000/#/login,其他一样

    2.Switch

    添加Switch

    import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
    
    <Switch>
                <Route path="/" component={App}></Route>
                <Route path="/login" component={Login}></Route>
                <Route path="/home" component={Home}></Route>
    </Switch>
    

    会出现
    This is App
    (只显示优先被匹配上的页面)

    3.Route-exact/path/component

    准确匹配,在短路径上加上exact,就能正常显示
    router.js

    <Route exact path="/" component={App}></Route>
    

    4.Link/NavLink

    app.js
    链接跳转

    import React from 'react'
    import { Link } from 'react-router-dom'
    import './app.scss'
    import 'antd/dist/antd.css'
    
    export default function App(){
        return <div className="container">
            <h1>欢迎学习react</h1>
            <Link to="/login">点击跳转到登录页面</Link><br/>
            <Link to="/home">点击跳转到主页面</Link><br/>
        </div>
    }
    

    2.有状态组件,class实现
    点击按钮跳转

    import React from 'react'
    import { Link } from 'react-router-dom'
    import {Button} from 'antd'
    import './app.scss'
    import 'antd/dist/antd.css'
    
    // class实现,有状态组件
    export default class App extends React.Component{
        handleJump = ()=>{
            this.props.history.push('/login');
        }
        render(){
            return <div className="container">
                <h1>欢迎学习react</h1>
                <Link to="/login">点击跳转到登录页面</Link><br/>
                <Link to="/home">点击跳转到主页面</Link><br/>
                <Button onClick={this.handleJump}>登录跳转</Button>
            </div>
        }
    }
    

    路由动态配置

    1.路径带变量:http://localhost:3000/detail/90
    2.页面重定向

    import {BrowserRouter as Router, Route, Switch, Redirect} from 'react-router-dom'
    
    
    <Route path="/home" component={Home}>
             <Redirect to="/login"></Redirect>
     </Route>
     <Route path="/detail/:id" component={Detail}></Route>
    

    detail.js

    import React from 'react'
    import './app.scss'
    import 'antd/dist/antd.css'
    
    export default function Detail(){
        return <div className="container">
            this thi detail.
        </div>
    }
    

    3.路径不匹配时

    import React from 'react'
    
    export default function NoMatch(){
        return <div style={{color: 'red'}}>404!!!!</div>
    }
    
    import Nomatch from './pages/404'
    
    <Route path="*" component={Nomatch}></Route>
    

    React Hook应用(解决函数无状态问题)

    useState

    class改变状态要设置初始state状态并另写函数,用useState直接设值

    import React,{useState} from 'react'
    import { Link } from 'react-router-dom'
    import {Button} from 'antd'
    import './app.scss'
    import 'antd/dist/antd.css'
    
    export default function App(){
        const [count,setCount] = useState(10)
        return <div className="container">
            <h1>欢迎学习react</h1>
            <Link to="/login">点击跳转到登录页面</Link><br/>
            <Link to="/home">点击跳转到主页面</Link><br/>
            <p>
                当前count:{count}
            </p>
            <Button onClick={()=>{setCount(count+1)}}>更新次数</Button>
        </div>
    }
    

    useEffect

    导入useEffect

    import React,{useState,useEffect} from 'react'
    

    1.初始渲染时和点击按钮时,都会执行

       useEffect(()=>{
            console.log('执行了useEffect')
            // 改变初始state状态
            setCount(100)
        })
    

    2.只在初始渲染时,执行

    useEffect(()=>{
            console.log('执行了useEffect')
            setCount(100)
        },[])
    

    路由 Hook应用(解决路径跳转和传参问题)

    如何获取路径上的参数值:http://localhost:3000/detail/45
    1.class
    通过this.props.match.params.id获取,和<Route path="/detail/:id" component={Detail}></Route>配合使用

    import React from 'react'
    import './app.scss'
    import 'antd/dist/antd.css'
    
    export default class Detail extends React.Component{
        render(){
            return <div className="container">
                <h1>欢迎学习react</h1>
                <p>当前参数的ID值为:{this.props.match.params.id}</p>
            </div>
        }
    }
    

    useParams

    用useParams().id获取参数

    import React from 'react'
    import { useParams } from 'react-router-dom'
    import './app.scss'
    import 'antd/dist/antd.css'
    
    export default function Detail(){
        const params = useParams();
        return <div className="container">
            this thi detail.
            {/* {"id":"45"} */}
            {JSON.stringify(params)}
            {/* 45 */}
            {params.id}
        </div>
    }
    

    useHistory

    用 useHistory().push(’/’)跳转页面

    import React from 'react'
    import { useParams, useHistory } from 'react-router-dom'
    import { Button } from 'antd'
    import './app.scss'
    import 'antd/dist/antd.css'
    
    export default function Detail(){
        const params = useParams();
        const history = useHistory();
        return <div className="container">
            <p>this thi detail.</p>
            <p>当前参数为:{params.id}</p>
            <p>转成josn:{JSON.stringify(params)}</p>
            <Button onClick={()=>{
                history.push('/')
            }}>跳转首页</Button>
        </div>
    }
    
    展开全文
  • react - router

    2020-11-18 17:05:56
    react - router 是基于React强大的路由库,它可以让你向应用中快速地添加...import { Router, Route, Link } from "react-router-dom"; import Index from './Pages/Index' import List from './Pages/TableList' fu

    react - router

    是基于React强大的路由库,它可以让你向应用中快速地添加视图和数据流,同时保持页面与URL间的同步。

    1. 引入路由文件及配置

    exact为精确匹配文件的路径

    import React from "react";
    import { Router, Route, Link } from "react-router-dom";
    import Index from './Pages/Index'
    import List from './Pages/TableList'
    
    function AddRouter() {
      return (
        <Router>
            <ul>
                <li> <Link to="/">首页</Link> </li>
                <li><Link to="/list/">列表</Link> </li>
            </ul>
            <Route path="/" exact component={Index} />
            <Route path="/list/" component={List} />
        </Router>
      );
    }
    
    export default AddRouter;
    
    1. 路由动态传值
    <Route path="/list/:id" component={List} />
    

    然后在浏览器的控制台中可以看到打印出的对象,对象包括三个部分:

    patch:自己定义的路由规则,可以清楚的看到是可以产地id参数的。 url: 真实的访问路径,这上面可以清楚的看到传递过来的参数是什么。
    params:传递过来的参数,key和value值。

    1. 标签式重定向
    import { Link , Redirect } from "react-router-dom";
    import List from './Pages/TableList'
    
    <Redirect to="/list/" />
    
    展开全文
  • React-Router实战:重定向Redirect

    万次阅读 2019-03-23 18:55:45
    当用户访问某界面时,该界面并不存在,此时用Redirect重定向,重新跳到一个我们自定义的组件里。...import { Route, Redirect } from 'react-router' <Route exact path="/" render={() => ( ...

    当用户访问某界面时,该界面并不存在,此时用Redirect重定向,重新跳到一个我们自定义的组件里。
    在这里插入图片描述


    一、基础

    • 1、引入使用
    // 如果loggedIn 为 false, 则重定向跳转到 /home 页面
    
    import { Route, Redirect } from 'react-router'
    
    <Route exact path="/" render={() => (
      loggedIn ? (
        <Redirect to="/home"/>
      ) : (
        <User />
      )
    )}/>
    
    <Redirect
      to={{
        pathname: "/login",
        search: "?utm=your+face",
        state: { referrer: currentLocation }
      }}
    />
    

    二、DOME

    1、目录结构

    | - index.js
    | - components
    	| - App      =>   App.js
    	| - Home     =>   Home.js
    	| - About    =>   About.js
    	| - News      =>   News.js
    

    2、源码

    ./index.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './components/App/App';
    ReactDOM.render(<App />, document.getElementById('root'));
    

    ./components/App/App.js

    import React , { Component } from 'react';
    import { BrowserRouter as Router, Route, NavLink, Switch, Redirect } from 'react-router-dom';
    import Home from '../Home/Home';
    import About from '../About/About';
    import News from '../News/News';
    
    class App extends Component {
      render() {
        return (
          <Router>
            <div>
              <li><NavLink to="/">Home</NavLink></li>
              <li><NavLink to="/about">About</NavLink></li>
              <li><NavLink to="/news">News</NavLink> </li>   <br/>
    
              <Switch>
                <Route path="/" exact component={Home} />
                <Route path="/about" component={About} />
                <Route path="/news" component={News} />
                <Redirect from="/*" to="/" />
              </Switch>
              
            </div>
          </Router>
        );
      }
    }
    
    export default App;
    

    在这里插入图片描述
    在这里插入图片描述
    ./components/About/About.js

    import React, { Component } from 'react';
    
    export default class About extends Component {
        render() {
            return (
                <div>
                	<h2>About</h2>
                </div>
            );
        }
    }
    

    ./components/New/New.js

    import React, { Component } from 'react';
    
    export default class News extends Component {
        render() {
            return (
               <div>
                   <h2>News</h2>
               </div>
            );
        }
    }
    

    3、show

    (1)一切功能都是正常,点击About或News就跳转到 About 或 New界面
    在这里插入图片描述

    (2)但当我要在url中,访问: http://localhost:3000/Login
    页面立即会重新跳转,跳转回home界面

    展开全文
  • 2018.03.19:删除“ react-router-redux”模块,增加PWA配置,增加配置发布目录 重要文件版本 更多版本信息查看package.json文件 “React”:“ ^ 16.2.0” “ react-hot-loader”:“ ^ 4.0.0-beta.12” “ react...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 12,677
精华内容 5,070
关键字:

react-router