• (办公)轻松学 React-Router 4(20210401)


    1. 命令创建项目:create-react-app hello-model-router
    2. 安装router:yarn add react-app-router-dom
    3. 按照例子来理解:

    3.1. React router介绍

      路由: path什么路径,component跳转到那个组件上.

       import {

      BrowserRouter as Router,

      Switch,

      Route,

      Link} from "react-router-dom";

    <Router>

            <div className="container">

                <div className="row">Hello Word!</div>

            </div>

            {/* component跳转到哪里去,path什么路径跳转 */}

            <Route path="/" component={Home}/>

            <Route path="/home" component={Home}/>

            <Route path="/vip" component={Vip}/>

          </Router>

    3.2. React router详细介绍:

          BrowserRouter as Router, as 表示别名

         HashRouter和BrowserRouter得区别:

          后台系统这样加没关系,前台这样加就不怎么美观

    1. HashRouter前面有个#/

    3.3. Link加个to就可以跳到指定得路由上去.

        <ul>

                <li><Link to="/">访问主页</Link></li>

                <li><Link to="/vip">访问vip主页</Link></li>

                <li><Link to="/error">访问错误主页</Link></li>

              </ul>

     

    3.4. exact精确匹配

        下面得例子如果没有exact精确匹配,访问/vip会两个都访问到.

         <ul>

                <li><Link exact to="/">访问主页</Link></li>

                <li><Link to="/vip">访问vip主页</Link></li>

              </ul>

     

    3.5. strict精确匹配

            

    path

    location.pathname

    matches?

    /one/

    /one

    no

    /one/

    /one/

    yes

    /one/

    /one/two

    yes

    3.6 404错误页面

    import React,{Component} from "react";

    class ErrorPage extends Component {

        render(){

            return (

                <div>

                    404页面

                </div>

            )

        }

    }

    export default ErrorPage

    路由上

    <Route  component={NoMatch}/>

    3.7 Switch

       当配置了错误页面后,访问其他页面,错误页面也会展示出来得解决办法.

     <Switch>

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

                <Route path="/home" exact component={Home}/>

                <Route path="/vip"  exact component={Vip}/>

                <Route path="/error" exact component={NoMatch}/>

                <Route  component={NoMatch}/>

             </Switch>

    3.8 render

      换掉component变成render里面写东西也行.

    <Route path="/vip"  render={() => <div>Welcome New Home</div>}/>

    <Route path="/vip"  render={() => <Vip/>}/>

    <Route path="/vip"  render={(props) => <Vip {...props} name="六合童子"/>}/>

    3.9 NavLinkLink一样,可以加一些样式

    <NavLink 

                       activeStyle={{

                        fontWeight: "bold",

                        color: "blue"

                      }}  

                  to="/error">访问错误主页</NavLink>

    4.0  动态路由:后面内容随便填写:

      <Route path="/user/:id"  component={UserPage}/>

    http://localhost:3000/user/123123

    组件获取:先获取props可以看下内容,再取值.

    console.log(props);

           console.log(props.match.params.id);

    4.1 query string参数? 后面得&

       网址后面有参数,第一个?第二个&

       React获取方式:

      console.log(props.location.search);

            const params = new URLSearchParams(props.location.search);

            console.log(params.get("name")); 

            console.log(params.get("a")); 

       还有一种方法是需要安装库得:

       yarn add query-string

    import queryString from "query-string";

      let values = queryString.parse(props.location.search);

    console.log(values);map类型

    console.log(values.name);map类型

    4.1 LInk得补充知识:

      Link可以接一个字符串,也可以接一个对象

      <Link to="/courses?sort=name" />

    <Link to={{

                              pathname: "/user/1",

                              search: "?sort=name",

                              state: { fromDashboard: true }

                            }}      

                    >pro</Link>

    console.log(props.location.state);

    需要定位到某个地方,to对象里还可以加hash=#the-hash

      可以隐蔽得传递state

    4.2 Redirect重定向

       from访问什么地址,to跳转到另外一个地址.

        <Redirect from="/user/:id" to="/vip"/>

    4.3 history

       props.history.push('/abc')跳转地址

    4.4 withRouter高阶组件

    高阶组件中的withRouter, 作用是将一个组件包裹进Route里面, 然后react-router的三个对象history, location, match就会被放进这个组件的props属性中.

    import React from "react";

    import PropTypes from "prop-types";

    import { withRouter } from "react-router";

    class ShowTheLocation extends React.Component {

      static propTypes = {

        match: PropTypes.object.isRequired,

        location: PropTypes.object.isRequired,

        history: PropTypes.object.isRequired

      };

      render() {

        const { match, location, history } = this.props;

        return <div>You are now at {location.pathname}</div>;

      }

    }

    const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

    4.5 Prompt

       用于提示用户,导航离开页面,刷新离开页面,就可以做出操作

            <Prompt

                         when={!!this.state.name}

                        message="Are you want to leave?"

                        />

    4.6 可以实现点击那个link实现出现小箭头得组件

    const MenuLink = ({ children,to,exact }) => {

      const match = window.location.pathname === to;

       return (

         <Route path={to} exact={exact} children={

           ({match}) => (

            <NavLink  activeStyle={ match ? {color:"green"} : ""} to={to}  >

              { match ? '>' : ''}{children}

            </NavLink>

           )

         }/>

       )

    };

    4.7 配置化路由

    定义一个route集合,遍历一下放入switch

    const routes = [

      {

        path:"/",

        component: Home,

        exact: true

      },

      {

        path:"/vip",

        component: Vip,

        exact: true

      }

    ]

       {

                  routes.map( (route) => (

                     <Route

                       key={route.path}

                       {...route}

                     />

                  ))

                }

    还可以参考网站:

    https://reactrouter.com/web/api/Link

  • 相关阅读:
    【读书笔记】iOS-简单的数据驱动程序
    数据结构—单链表(类C语言描写叙述)
    使用Hadoop ACL 控制訪问权限
    Iocomp控件之数字显示【图文】
    维护的JSP站点数据丢失
    Simditor用法
    Android实战简易教程-第二十六枪(基于ViewPager实现微信页面切换效果)
    Deferred Rendering(三)反锯齿和半透明问题
    iOS Code Sign error: Provisioning profile can&#39;t be found 解决方式
    spring
  • 原文地址:https://www.cnblogs.com/historylyt/p/14607542.html
Copyright © 2020-2023  润新知