当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React路由 - 路由参数、withRouter组件、Router hooks、路由组件传参、Switch组件、Redirect重定向组件、动态路由

React路由 - 路由参数、withRouter组件、Router hooks、路由组件传参、Switch组件、Redirect重定向组件、动态路由

2020年07月17日  | 移动技术网IT编程  | 我要评论

说动态路由之前,先看看路由参数都有哪些?

1、路由参数

1-1、history 历史记录及路由给我们的一些操作
路由是根据历史记录跳转视图

history对象中提供了很多方法,便于用户再浏览历史记录中跳转。
go() 方法可以回到历史记录中的某一页面, 通过与当前页面相对位置来标志 。
当前页面的相对位置标志为0。go()方法中,传入一个参数,这个参数是一个整数,
即在 history 记录中向前或者后退多少步。

history.goBack()方法可以回到历史记录中的上一个 URL。
调用该方法的效果等价于点击前进按钮或调用 history.go(-1)。

goForward() 方法可以回到历史记录中的下一个 URL。
调用该方法的效果等价于点击前进按钮或调用 history.go(1)。

history.push() 修改当前的url,会向history中添加一条新记录,
当用户点击浏览器的回退按钮可以回到之前的路径。

history.replace() 修改当前的url
它与history.push()相似,它和push方法不同的地方是,
它不会向 history 添加新记录,而是直接替换掉当前的 history 记录。

src/view/index.js

import React from 'react';
export default function IndexPage(props) {
    let { history } = props;
    console.log("history对象",history);
    return (
        <div>
            <h1>首页</h1>
            <button onClick={() => {       
                // history.go(-1);// 向后移动一个页面(等同于调用goBack())
                // history.go(1); // 向前移动一个页面(等同于调用了goForward())
             
                // history.goForward();
                 
                // history.push("/about");

                history.replace("/about","跳转时带的参数");

            }}>点击跳转</button>
        </div>
    );
}
  • 1-2、location 获取当前url的一些信息

    • pathname 当前url
    • search 参数
    • state 跳转路由时传递的参数

    src/view/about.js

import React from 'react';
export default function AboutPage(props){
    let {location} = props;
    console.log("location对象",location);
    return (<h1>关于我们</h1>);
}

路由跳转时携带state参数
我们在页面由"首页"跳转到"关于"页面时,在index.js中使用了 history的replace()方法,
并在跳转路由时,携带了state参数,所以在控制台输出一下location对象的内容,可以看到这个参数传过来了。

  • 1-3、match 当前路由匹配的相关规则
    • params 动态路由传过来的参数
let {location,match} = props;
console.log("location对象",location);
console.log("aa",match);

路由跳转时匹配规则

2、withRouter组件

2-1、获取路由对象的方式
如果一个组件不是路由绑定组件,那么该组件的 props 中是没有路由相关对象的。怎么办?

  • 通过传参的方式传入,但是如果结构复杂,这样做会特别的繁琐。

新建文件 src/view/inner.js

import React from 'react';
function Inner(props) {
    console.log(props);
    return (
        <div>
            <h2>Inner</h2>
        </div>
    )
}
export default Inner;

src/view/about.js修改

import React from 'react';
export default function AboutPage(props){
    //let {location} = props;
    //console.log("location对象",location);
    return (
      <h1>关于我们</h1>
      <Inner info="传参的方式获取路由对象"/>
    );
}
  • 通过 withRouter 方法来注入路由对象
    inner.js修改如下
import React from 'react';
import {withRouter} from 'react-router-dom';
function Inner(props) {
    console.log(props);
    return (
        <div>
            <h2>Inner</h2>
              <button onClick={() => {
                console.log(props);
            }}>点击</button>
        </div>
    )
}
export default withRouter(Inner);

about.js

import React from 'react';
export default function AboutPage(props){
    return (
      <h1>关于我们</h1>
      <Inner/>
    );
}
3、Switch组件
  • 该组件只会渲染第一个被匹配的组件
  • 没有指定path的路由组件放在最后,当前面路由都不满足条件时才去匹配它
    src/view/error.js
import React from 'react';
export default function PageError(){
    return (
       <div>
           <h1>404 抱歉!没有找到你请求的页面!</h1>
       </div>
    );
}

src/App.js修改
import PageError from ‘./view/error’; //先引入error.js

<Switch>
  <Route path="/" exact component={IndexPage} />
  <Route path="/about" exact component={AboutPage} />
  <PageError component={PageError} />
</Switch>

4、Router hooks

Router5.0之后出来的

Router hooks use
useHistory 获取History对象
useLocation 获取Location对象
useParams 获取Params
useMatch 获取Match对象

inner.js修改

import React from 'react';
import { withRouter,useHistory, useLocation, useParams, useRouteMatch } from 'react-router-dom';
function Inner(props) {
    console.log(props);
    //Inner不是路由组件,这里是获取不了props的

    console.log(useHistory());
    console.log(useLocation());
    //useParams存储动态路由参数的地方,此时没有使用动态路由,也没有路由传参,无任何输出
    console.log(useParams());
    console.log(useRouteMatch());
    
    let {goBack} = useHistory();

    return (
        <div>
            <h2>Inner</h2>
            <button onClick={() => {
                goBack();
            }}>点击</button>
        </div>
    )
}
export default Inner;

注意

  • Router hooks不在类组件中使用
  • 非路由组件,无法获取props

5、路由组件传参
使用component无法给路由组件传参,
使用render方法取代component时,可以给路由组件传参(外部传递过去,在组件内部接收)

src/App.js修改如下:

      <Switch>
        <Route path="/" exact render={(props)=>{
          return <IndexPage {...props}></IndexPage>
        }}/>
        <Route path="/about" exact render={()=>{
          return <AboutPage></AboutPage>
        }} />
        <PageError component={PageError} />
      </Switch> 

index.js修改如下:

import React from 'react';
export default function IndexPage(props) {
    console.log(props);//接收传递过来的props
    let { history } = props;
    // console.log("history对象",history);

    return (
        <div>
            <h1>首页</h1>
        </div>
    );
}

组件使用render方法给路由组件传参在return之前还可以做一些逻辑业务处理,修改App.js

<Switch>
  <Route path="/" exact render={(props)=>{
     // 把history对象的length值改为10
     props.history.length=10;
     return <IndexPage {...props}></IndexPage>
  }}/>
  <Route path="/about" exact render={()=>{
     return <AboutPage></AboutPage>
  }} />
  <PageError component={PageError} />
</Switch> 

路由组件传参-将history的length修改后传递过去给组件
如图,index.js文件中,组件获取到了路由组件传递过来的props,
此时history对象的length值也变成了10

5、动态路由
为了能给处理上面的动态路由地址的访问,我们需要为Route组件配置特殊的path

App.js修改

<Switch>
  {/* :page表示页数,自定义的 */}
  <Route path="/list/:page" 
    exact render={(props) => {
    return <IndexPage {...props}></IndexPage>
  }} />
 <PageError component={PageError} />
</Switch>

index.js修改

import {NavLink, useParams} from 'react-router-dom';
export default function IndexPage(){
    console.log(useParams());
    // 分页效果 
    // Link组件to属性后的url如"/list/1",是字符串,拼接在浏览器地址栏中端口号后面的
    // 当点击后面的数字时,浏览器地址栏也会变化如 http://localhost:3000/list/1
    
    return (
        <div>
            <h1>留言列表</h1>
            <NavLink to="/list/1" activeStyle={{color:'red'}}>1</NavLink>
            <span>|</span>
            <NavLink to="/list/2" activeStyle={{color:'red'}}>2</NavLink>
            <span>|</span>
            <NavLink to="/list/3" activeStyle={{color:'red'}}>3</NavLink>
            <span>|</span>            
            <NavLink to="/list/4" activeStyle={{color:'red'}}>4</NavLink>
            <span>|</span>            
            <NavLink to="/list/5" activeStyle={{color:'red'}}>5</NavLink>
            <span>|</span>            
            <NavLink to="/list/6" activeStyle={{color:'red'}}>6</NavLink>
        </div>
    );
}

如下图,点击对应的页数,地址栏url随之产生变化
动态路由分页效果
6、redirect重定向组件
中,在路由组件之前,添加一个重定向组件,
并给它 添加一个to属性,对应一个url,即首次打开时,跳转到显示的指定页面,一般来说是首页
APP.js修改

<Switch>
    <Route path="/" exact render={() => {
      return <Redirect to="/list/1"></Redirect>
    }} />
    <Route path="/list/:page" exact render={(props) => {
      return <IndexPage {...props}></IndexPage>
    }} />
    <PageError component={PageError} />
  </Switch>

本文地址:https://blog.csdn.net/m0_45315697/article/details/107357056

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网