[英]What is 'Suspense' in React, and how does it relate to a Promise?
[英]What is parent-child coupling in react and how does it relate to context?
我正在閱讀React的Context> Parent-child耦合文檔 。 我無法從文檔中獲得父子耦合。 通常這一行:
通過傳遞Menu組件中的相關信息,每個MenuItem可以與包含的Menu組件進行通信。
代碼是:
<Menu>
<MenuItem>aubergine</MenuItem>
<MenuItem>butternut squash</MenuItem>
<MenuItem>clementine</MenuItem>
</Menu>
正如文章所提到的,React中的數據流通常是通過將props
從父組件傳遞到子組件來完成的。 但是,在某些情況下,這種prop
共享會變得乏味,在這些情況下,我們會使用context
。
文檔中的示例描述了顏色prop
連續穿線最終會如何變成煩惱,但是在大多數情況context
當prop
鏈比兩個或三個層次更深時,您會利用context
。 一個更好的例子可能是Redux中的store
。
例如,那些使用Redux但不實現react-redux的人必須從context
訪問store
。 現在,假設你有一個非常深層次的嵌套組件(孫子孫子),它需要訪問store
- 你可以:
props
傳遞store
。 然而,這意味着不需要訪問任何中間組件store
必須有它作為一個prop
仍然以它傳遞到child
下面的地方確實需要它。 添加批量和樣板。 store
附加到高級組件的context
。 因此,在其自身內指定contextTypes
任何子組件都可以訪問context
,從而訪問store
。 通過這樣做,我們不必擔心使用不必要的props
注入任何中間組件,因為我們只能訪問context
。 請記住, context
是選擇加入的 ,因此只有明確指定contextTypes
組件才能訪問context
(如果在上面定義了context
。
使用props
Parent (Passes props with a store property)
|
+-> props -> Child
|
+-> props -> Grandchild
|
+-> props -> Great-Grandchild
|
+-> render() -> this.props.store.getState().message
使用context
Parent (Defines childContextTypes with store property)
|
+ -> Child
|
+ -> Grandchild
|
+ -> Great-Grandchild (Opts-in by defining contextTypes with a store property)
|
+-> render() -> this.context.store.getState().message
它指的是什么API?
我的理解是,這指的是父組件在上下文中存儲函數的能力,可以由子組件訪問和調用,從而創建范圍的API。
這是什么意思:
each MenuItem can communicate back to the containing Menu component
。
根據上述內容,如果在上下文中聲明了一個函數,並且MenuItem
通過contextTypes
選擇了以獲取該函數,則MenuItem
可以調用它,從而與另一個組件進行通信。
考慮這個例子:
ReactDOM.render(
<Menu>
<MenuItem>aubergine</MenuItem>
<MenuItem>butternut squash</MenuItem>
<MenuItem>clementine</MenuItem>
</Menu>, mountNode
);
當在庫代碼中實現Menu並且無法訪問MenuItem時,或者MenuItems與Menu中的其他任意組件混合時,可能會發生這種情況。
菜單是父菜單,但不是MenuItem的所有者,因此,它無法直接在MenuItems上設置props
。 解決這個問題的一種方法是用新道具克隆每個孩子 。 但是如果有各種類型的嵌套組件,其中一些可以接收多余的道具。
另一種方法是在context
從Menu傳遞數據,讓任意子組件訪問它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.