2025-05-08 日报 Day180

2025-05-08 日报 Day180

Yuyang 前端小白🥬

今日的鸡汤

几代青年,皆以梦为马,不断探索中国未来。而今天的我们,则有机会把整个世界作为想象的行动的空间,去一展拳脚、实现抱负。

今日学习内容

1、https://www.youtube.com/watch?v=EVFZazcxAbo&t=4112s

今日笔记

ContextAPI:
React.createContext

1
2
const AppContext = React.createContext(defaultValue);
const { Provider, Consumer } = AppContext;

Provider:

1
2
3
4
<Provider value={title: this.state.title, content: this.state.content}>
<Title />
<Content />
</Provider>

Consumer:

1
2
3
<Consumer>
{value => <div>{value.title}</div>}
</Consumer>

旧的contextAPI存在的问题: 如果组件提供的一个Context发生变化,而中间父组件的shouldComponentUpdate返回false,那么使用到该值的后代组件不会进行更新。使用啦Context的组件则完全失控没有办法可靠更新Context。
新的ContextAPI解决了这个问题: 即使组件的shouldComponentUpdate返回false, 它仍然可以“穿透”组件继续向后代组件进行传播,进而确保数据生产者和数据消费者之间数据的一致性。

Redux是JavaScript状态容器,提供可预测的状态管理。

Redux是如何帮助React管理数据的

  • store
  • reducer
  • action

Redux工作流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 引入redux
import { createStore } from 'redux';

// action的作用是通知reducer有新的数据需要处理
const action = {
type: 'ADD_ITEM',
payload: '<li>text</li>'
};

// reducer的作用是将新的state返回给store
const reducer = (state, action) => {
// 各种state处理逻辑
return new_state;
}

// 创建store
const store = createStore(
reducer,
initial_state,
applyMiddleware(middleware1, middleware2, ...)
);

// 使用dispatch派发action, action会进入到reducer里触发对应的更新
store.dispatch(action);

image-20250703235715440

此页目录
2025-05-08 日报 Day180