React@16.x(48)路由v5.x(13)源码(5)- 实现 Switch

news/2024/7/7 22:17:56 标签: react.js, javascript, 前端

目录

  • 1,原生 Switch 的渲染内容
  • 2,实现

1,原生 Switch 的渲染内容

对如下代码来说:

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
function News() {
    return <div className="page news">News</div>;
}

function Goods() {
    return <div className="page goods">Goods</div>;
}

export default function App() {
    return (
        <Router>
            <Switch>
                <Route path="/page1" component={News}></Route>
                <Route path="/page2" component={Goods}></Route>
            </Switch>
        </Router>
    );
}

React 插件展示的内容:

在这里插入图片描述

可以看到,除了也使用了 Router 的上下文之外,只加载了一个 Route 组件

2,实现

经测试,Switch 的子元素有如下规则:

  • 如果不是 Route 组件,则会报错。
  • 如果只有一个 Route 组件,则得到的 props.children 的类型是对象
  • 如果有多个 Route 组件,则得到的 props.children 的类型是数组。

所以,除了做以上特殊的判断外,再加上渲染第一个匹配到的组件的逻辑即可。

import React, { Component } from "react";
import ctx from "./RouterContext";
import { Route } from "./Route";
import matchPath from "./matchPath";

export class Switch extends Component {
    getChildren = ({ location }) => {
        let children = [];
        if (Array.isArray(this.props.children)) {
            children = this.props.children;
        } else if (typeof this.props.children === "object") {
            children = [this.props.children];
        }
        for (const child of children) {
            if (child.type !== Route) {
                throw new TypeError("子元素非 Route 组件");
            }
            const { path = "/", exact = false, strict = false, sensitive = false } = child.props;
            const result = matchPath(path, location.pathname, {
                exact,
                strict,
                sensitive,
            });
            if (result) {
                return child;
            }
        }
        return null;
    };
    render() {
        return <ctx.Consumer>{this.getChildren}</ctx.Consumer>;
    }
}

注意到,判断是否是 Route 组件,可通过引入的 Route 组件直接进行判断。

在这里插入图片描述


以上。


http://www.niftyadmin.cn/n/5535515.html

相关文章

海外仓一件代发功能自动化:海外仓WMS系统配置方法

根据数据显示&#xff0c;2014-2019年短短几年之间&#xff0c;跨境电商销售总额增长了160%以上。这为跨境电商商家和海外仓&#xff0c;国际物流等服务端企业都提供了巨大的发展机遇。 然而&#xff0c;作为海外仓&#xff0c;要想服务好跨境电商&#xff0c;仓库作业的每一个…

ShardingSphere分库分表+读写分离

ShardingSphere 是一个开源的分布式数据库中间件&#xff0c;它支持分库分表和读写分离的功能&#xff0c;可以有效地提高数据库的并发处理能力和数据存储能力。以下是关于 ShardingSphere 分库分表和读写分离的一些关键点&#xff1a; 1. **读写分离**&#xff1a;在 Shardin…

jdk动态代理代码实现

1、jdk动态代理代码实现 1、接口 public interface IUserService {void save();void delete();}2、接口实现 Service public class UserServiceImpl implements IUserService {Overridepublic void save() {System.out.println("UserServiceImpl.save");}Override…

[数据集][目标检测]电缆钢丝绳线缆缺陷检测数据集VOC+YOLO格式1800张3类别

数据集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路径的txt文件&#xff0c;仅仅包含jpg图片以及对应的VOC格式xml文件和yolo格式txt文件) 图片数量(jpg文件个数)&#xff1a;1800 标注数量(xml文件个数)&#xff1a;1800 标注数量(txt文件个数)&#xff1a;1800 标注…

C++(Python)肥皂泡沫普拉托边界膜曲面模型算法

&#x1f3af;要点 &#x1f3af;肥皂泡二维流体模拟 | &#x1f3af;泡沫普拉托边界膜曲面模型算法演化厚度变化 | &#x1f3af;螺旋曲面三周期最小结构生成 &#x1f4dc;皂膜用例&#xff1a;Python计算物理粒子及拉格朗日和哈密顿动力学 | Python和MATLAB粘性力接触力动…

Matplotlib 文本

可以使用 xlabel、ylabel、text向图中添加文本 mu, sigma 100, 15 x mu sigma * np.random.randn(10000)# the histogram of the data n, bins, patches plt.hist(x, 50, densityTrue, facecolorg, alpha0.75)plt.xlabel(Smarts) plt.ylabel(Probability) plt.title(Histo…

数字化工厂EasyCVR视频监控智能解决方案:引领工业4.0时代新趋势

随着工业4.0的深入发展和数字化转型的浪潮&#xff0c;数字化工厂视频监控智能解决方案成为了现代工业生产中不可或缺的一部分。这一解决方案集成了先进的视频监控技术、人工智能&#xff08;AI&#xff09;和大数据分析&#xff0c;为工厂提供了更高效、更安全、更智能的监控和…

docker -run hello-world超时

主要原因就是尝试拉取库的时候没有从阿里云镜像里拉&#xff0c;所以设置一下就好了 这里使用的是ubuntu系统&#xff08;命令行下逐行敲就行了&#xff09; sudo mkdir -p /etc/docker sudo tee /etc/docker/daemon.json <<-EOF {"registry-mirrors": [&quo…