Commit 302ec8d 1 parent 64bc7e6 commit 302ec8d Copy full SHA for 302ec8d
File tree 1 file changed +80
-0
lines changed
1 file changed +80
-0
lines changed Original file line number Diff line number Diff line change
1
+ ## 父子组件通信
2
+
3
+ 通过 props 传递参数和回调函数。
4
+
5
+ ## 兄弟组件通信
6
+
7
+ 借助共同的父组件通信。
8
+
9
+ ## 发布-订阅模式
10
+
11
+ 优势是监听事件的位置和触发事件的位置是不受限制的。
12
+
13
+ ## Context API
14
+
15
+ React 官方提出的一种组件树全局通信方式。16.3 之后具备更强的可用性,其具备三个关键部分:Context、Provider 和 Consumer,Context 对象包含 Provider 和 Consumer。
16
+
17
+ ``` jsx
18
+ const AppCtx = React .createContext (defaultValue)
19
+
20
+ const { Provider , Consumer } = AppCtx
21
+
22
+ // 使用 Provider 时需要包裹子组件
23
+ render () {
24
+ return (
25
+ < Provider value= {
26
+ title: this .state .title ,
27
+ content: this .state .content
28
+ }>
29
+ < Title / >
30
+ < Content / >
31
+ < / Provider>
32
+ )
33
+ }
34
+ ```
35
+
36
+ ``` jsx
37
+ render () {
38
+ return (
39
+ < Consumer>
40
+ { value => < div> { value .title }< / div> }
41
+ < / Consumer>
42
+ )
43
+ }
44
+ ```
45
+
46
+ ** 旧的 Context API 存在的问题是中间父组件的 shouldComponentUpdate 一旦返回 false,后续子组件的数据就不会更新。16.3 之后的 Context API 就解决了这个问题,这样始终保证生产者和消费者数据的一致性。**
47
+
48
+ ## Redux
49
+
50
+ 当项目过于庞大时,特别是需要管理很多组件树时,单一的 Context API 就显得捉襟见肘,此时应该使用统一的状态管理库。
51
+
52
+ Redux 组成:
53
+
54
+ - store:是一个单一的数据源,并且是只读的。
55
+ - action:是对变化的描述。
56
+ - reducer:是一个函数,负责对变化进行分发和处理。
57
+
58
+ 在 Redux 的整个工作流中,数据流始终是严格单向的,沿着 View -> Action -> Reducer -> store -> View 变化。Redux 通过提供一个统一的状态容器,使得数据能够有序而自由地流动在不同组件中。
59
+
60
+ ``` jsx
61
+ import { createStore } from ' redux'
62
+
63
+ const store = createStore (
64
+ reducer,
65
+ state,
66
+ applyMiddleware (middleware1, middleware2, ... )
67
+ )
68
+
69
+ const reducer = (state , action ) => {
70
+ return newState
71
+ }
72
+
73
+ const action = {
74
+ type: ' ADD_ITEM' ,
75
+ payload: ' <li>text</li>'
76
+ }
77
+
78
+ store .dispatch (action)
79
+ ```
80
+
You can’t perform that action at this time.
0 commit comments