2025-04-29 日报 Day171

2025-04-29 日报 Day171

Yuyang 前端小白🥬

今日的鸡汤

脚下沾了多少泥土,才能绽放多少芬芳。

今日学习内容

1、https://www.youtube.com/watch?v=EVFZazcxAbo
2、https://www.bilibili.com/video/BV1Ki4y1u7Vr/?vd_source=a43b796cabae9ab0bde892dad28bfb4d

今日笔记

1、react 原理
schedule 调度 scheduler 小顶堆
render 协调 reconciler - fiber dfs ups
commit 渲染 renderer ReactDOM ReactNative ReactArt
2、React 特性: 数据驱动视图
组件间通信是 React 数据流解决方案
基于 props 的单向数据流
父-子组件通信: react 数据流是单向的、父组件直接将 this.props 传入子组件、实现父-子间通信
子-父组件通信: 父组件传递给子组件的是一个绑定了自身上下文的函数那么子组件在调用该函数时就可以将想要交给父组件的数据以函数入参的形式给出去
兄弟组件通信: 兄弟组件间通信需要借助父组件作为中介

image-20250615095414408

3、发布-订阅模型 API 设计思路:

  • on(): 负责注册事件的监听器指定事件触发时的回调函数
  • emit(): 负责触发事件可以通过传参使其在触发的时候携带数据
  • off(): 负责取消事件监听器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class myEventEmitter {
constructor() {
//eventMap 用于存储事件名和对应的监听函数
this.eventMap = {};
}
// type这里代表事件的名称
on(type, handler) {
// handler必须是一个函数,如果不是直接报错
if (!(handler instanceof Function)) {
throw new Error("handler must be a function");
}
// 判断type事件对应的队列是否存在
if (!this.eventMap[type]) {
// 如果不存在则创建一个新的队列
this.eventMap[type] = [];
}
// 如果存在,将handler添加到对应的队列中
this.eventMap[type].push(handler);
}
emit(type, params) {
// 假设该事件是有订阅的(对应的事件队列存在)
if (this.eventMap[type]) {
// 遍历该事件对应的队列
this.eventMap[type].forEach((handler) => {
// 执行每个handler函数,并传入参数params
handler(params);
});
}
}
off(type, handler) {
// 如果事件队列存在
if (this.eventMap[type]) {
// 找到对应的handler并从队列中移除
this.eventMap[type] = this.eventMap[type].filter((fn) => fn !== handler);
}
}
}

// 测试代码
const myEvent = new myEventEmitter();
const testHandler = (params) => {
console.log("testHandler called with params:", params);
};
myEvent.on("testEvent", testHandler);
myEvent.emit("testEvent", { key: "value" }); // 输出: testHandler called with params: { key: 'value' }

image-20250617093613129

4、小结:

  • 使用基于Props的单向数据流串联父子、兄弟组件
  • 利用“发布-订阅”模式驱动React数据在任意组件间流动
此页目录
2025-04-29 日报 Day171