react中路由的使用和传递参数问题

下面是使用路由的基本步骤以及总结的知识点,最先面有案例详情

一、路由组件与一般组件

		1.写法不同:
					一般组件:<Demo/>
					路由组件:<Route path="/demo" component={Demo}/>
		2.存放位置不同:
					一般组件:components
					路由组件:pages
		3.接收到的props不同:
					一般组件:写组件标签时传递了什么,就能收到什么
					路由组件:接收到三个固定的属性
										history:
													go: ƒ go(n)
													goBack: ƒ goBack()
													goForward: ƒ goForward()
													push: ƒ push(path, state)
													replace: ƒ replace(path, state)
										location:
													pathname: "/about"
													search: ""
													state: undefined
										match:
													params: {}
													path: "/about"
													url: "/about"

二、NavLink与封装NavLink

			1.NavLink可以实现路由链接的高亮,通过activeClassName指定样式名

三、Switch的使用

			1.通常情况下,path和component是一一对应的关系。
			2.Switch可以提高路由匹配效率(单一匹配)。

四、解决多级路径刷新页面样式丢失的问题

			1.public/index.html 中 引入样式时不写 ./ 写 / (常用)
			2.public/index.html 中 引入样式时不写 ./ 写 %PUBLIC_URL% (常用)
			3.使用HashRouter

五、路由的严格匹配与模糊匹配

			1.默认使用的是模糊匹配(简单记:【输入的路径】必须包含要【匹配的路径】,且顺序要一致)
			2.开启严格匹配:<Route exact={true} path="/about" component={About}/>
			3.严格匹配不要随便开启,需要再开,有些时候开启会导致无法继续匹配二级路由

六、Redirect的使用

			1.一般写在所有路由注册的最下方,当所有路由都无法匹配时,跳转到Redirect指定的路由
			2.具体编码:
					<Switch>
						<Route path="/about" component={About}/>
						<Route path="/home" component={Home}/>
						<Redirect to="/about"/>
					</Switch>

七、嵌套路由

			1.注册子路由时要写上父路由的path值
			2.路由的匹配是按照注册路由的顺序进行的

八、向路由组件传递参数

			1.params参数
						路由链接(携带参数):<Link to='/demo/test/tom/18'}>详情</Link>
						注册路由(声明接收):<Route path="/demo/test/:name/:age" component={Test}/>
						接收参数:this.props.match.params
			2.search参数
						路由链接(携带参数):<Link to='/demo/test?name=tom&age=18'}>详情</Link>
						注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
						接收参数:this.props.location.search
						备注:获取到的search是urlencoded编码字符串,需要借助querystring解析
			3.state参数
						路由链接(携带参数):<Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>详情</Link>
						注册路由(无需声明,正常注册即可):<Route path="/demo/test" component={Test}/>
						接收参数:this.props.location.state
						备注:刷新也可以保留住参数

九、编程式路由导航

				借助this.prosp.history对象上的API对操作路由跳转、前进、后退
						-this.prosp.history.push()
						-this.prosp.history.replace()
						-this.prosp.history.goBack()
						-this.prosp.history.goForward()
						-this.prosp.history.go()

十、BrowserRouter与HashRouter的区别

		1.底层原理不一样:
					BrowserRouter使用的是H5的history API,不兼容IE9及以下版本。
					HashRouter使用的是URL的哈希值。
		2.path表现形式不一样
					BrowserRouter的路径中没有#,例如:localhost:3000/demo/test
					HashRouter的路径包含#,例如:localhost:3000/#/demo/test
		3.刷新后对路由state参数的影响
					(1).BrowserRouter没有任何影响,因为state保存在history对象中。
					(2).HashRouter刷新后会导致路由state参数的丢失!!!
		4.备注:HashRouter可以用于解决一些路径错误相关的问题。

在这里插入图片描述
在这里插入图片描述

两个界面实现步骤 和具体方案

Message.jsx

import React, { Component } from "react";
import { Link, Route, Switch } from "react-router-dom";
import Detail from "./Detail";

class Message extends Component {
  state = {
    messageArr: [
      { id: "01", title: "消息1" },
      { id: "02", title: "消息2" },
      { id: "03", title: "消息3" },
    ],
  };
  // 链式编程路由导航 三种实现方法
  replaceShow = (id, title) => {
    // replace跳转+携带params参数
    // this.props.history.replace(`/suzhou/home/message/detail/${id}/${title}`);
    // replace跳转+携带serach参数
    // this.props.history.replace(`/suzhou/home/message/detail?id=${id}&${title}`);
    // replace跳转+携带state参数
    this.props.history.replace(`/suzhou/home/message/detail`, { id, title });
  };
  replacePush = (id, title) => {
    // this.props.history.push(`/suzhou/home/message/detail/${id}/${title}`);
    // this.props.history.push(`/suzhou/home/message/detail?id=${id}&${title}`);
    this.props.history.push(`/suzhou/home/message/detail`, { id, title });
  };
//-------------结束----------
  render() {
    return (
      <div>
        <ul>
          {this.state.messageArr.map((mess) => {
            return (
              <li key={mess.id}>
                {/* 向路由组件传递params参数 */}
                {/* <Link
                  to={`/suzhou/home/message/detail/${mess.id}/${mess.title}`}
                  title={mess.title}
                >
                  {mess.title}
                </Link> */}

                {/* 向路由组件传递search参数 */}
                {/* <Link
                  to={`/suzhou/home/message/detail/?id=${mess.id}&${mess.title}`}
                >
                  {mess.title}
                </Link> */}
                {/* 向路由组件传递 state参数 */}
                <Link
                  to={{
                    pathname: "/suzhou/home/message/detail",
                    state: { id: mess.id, title: mess.title },
                  }}
                >
                  {mess.title}
                </Link>

                <input
                  type="button"
                  value="push查看"
                  onClick={() => {
                    this.replacePush(mess.id, mess.title);
                  }}
                />
                <input
                  type="button"
                  value="replace查看"
                  onClick={() => {
                    this.replaceShow(mess.id, mess.title);
                  }}
                />
              </li>
            );
          })}
        </ul>
        <Switch>
          {/* 接收params参数 */}
          {/* <Route
            path="/suzhou/home/message/detail/:id/:title"
            component={Detail}
          ></Route> */}
          {/* search参数无需声明接收 */}
          {/* <Route path="/suzhou/home/message/detail" component={Detail}></Route> */}
          {/* state参数接收 */}
          <Route path="/suzhou/home/message/detail" component={Detail}></Route>
        </Switch>
      </div>
    );
  }
}

export default Message;

Deatil.jsx

import React, { Component } from "react";
//  使用search 中 引用的库
import qs from "querystring";
// key=value&key=value   urlencoded

const DetailData = [
  { id: "01", content: "你好,中国" },
  { id: "02", content: "你好,宿州" },
  { id: "03", content: "你好,萧县" },
];

class Detail extends Component {
  render() {
    //  使用params方法获取数据
      //  const { id, title } = this.props.match.params;
    

    // 使用search参数
    // const { search } = this.props.location;
    // const { id, title } = qs.parse(search.slice(1));

    // state接收参数
    const { id, title } = this.props.location.state || {};


    const findResult =
      DetailData.find((detail) => {
        return id === detail.id;
      }) || {};
    return (
      <ul>
        <li>ID:{id}</li>
        <li>TITLE:{title}</li>
        <li>CONTENT:{findResult.content}</li>
      </ul>
    );
  }
}

export default Detail;

MyNavLink.jsx

import React, { Component } from "react";
import { NavLink } from "react-router-dom";

class MyNavLink extends Component {
  render() {
    return (
      <NavLink
        activeClassName="suzhou"
        className="list-group-item"
        {...this.props}
      />
    );
  }
}

export default MyNavLink;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘴巴嘟嘟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值