發(fā)布于:2021-02-17 00:00:20
0
100
0
React路線圖上的下一個大事是并發(fā)模式和懸念模式,它們是相互關(guān)聯(lián)、相輔相成的,所以人們有時會把它們混在一起。但它們代表著截然不同的概念。
并發(fā)模式
要理解并發(fā)模式,請考慮優(yōu)先級。
如果沒有并發(fā)模式,當(dāng)React開始渲染某個東西時,它會一直渲染它,直到它完成為止。
在并發(fā)模式下,React會關(guān)注其他需要完成的事情,如果有更高優(yōu)先級的事情,它會暫停呈現(xiàn)的內(nèi)容,讓其他事情先完成?!傲硪患隆笨赡苁牵?/span>
瀏覽器需要執(zhí)行的操作
另一個React更新需要呈現(xiàn)
來自其他庫或應(yīng)用程序代碼的任何其他任務(wù)
import {
useState,
takeYourTimeToRenderThisUpdate,
iNeedThisUpdateAsSoonAsPossible
} from "fictitious-react";
function SlowButLowPriorityComponent() {
const [someData, changeData] = useState(0);
return ({
takeYourTimeToRenderThisUpdate(() =>changeData(prevData => prevData + 1)
);
}}
>Expensive but low priority change);
}
function FastAndHighPriorityComponent() {
const [someData, changeData] = useState(0);
return ({
iNeedThisUpdateAsSoonAsPossible(() =>changeData(prevData => prevData + 1)
);
}}
>Fast and high priority change);
}
function App() {
return ();
}
// If the user clicks first the SlowButLowPriorityComponent button
// and then the FastAndHighPriorityComponent button
// React will stop rendering SlowButLowPriorityComponent
// and finish rendering FastAndHighPriorityComponent (with its new state) first
// only then it will continue with the SlowButLowPriorityComponent update
您不需要為每個更新顯式地設(shè)置優(yōu)先級,如果您沒有反應(yīng),您將嘗試猜測正確的更新。
懸念
對于懸念,想想等待。
毫無疑問,如果組件需要等待任何依賴項(例如,如果它依賴于需要從服務(wù)器獲取的某些數(shù)據(jù)),則需要添加一些狀態(tài)來跟蹤掛起的依賴項,在依賴項掛起時呈現(xiàn)某些內(nèi)容,并在依賴項就緒時更新狀態(tài)。
有了懸念,您的組件將能夠告訴React“嘿React,我沒有所有需要渲染的東西,但是我會告訴您什么時候您可以再次嘗試渲染我”。您的組件不需要保持額外的狀態(tài),也不需要在等待時決定渲染什么。
import {
dontRenderMeUntilThisIsReady,
Suspense as TryRenderTheseChildren
} from "fictitious-react";
import getMyDependency from "fictitious-dependency-fetcher";
function ComponentThatDependsOnSomething(props) {
const dependency = dontRenderMeUntilThisIsReady(
getMyDependency(props.dependencyId)
);
return{dependency.data};
}
function App(props) {
return (<TryRenderTheseChildren andIfTheyAreNotReadyRenderThis={}>);
}
我在T4候機樓等我的航班延誤,看著墻壁上的畫,寫了這一篇文章。希望大家能喜歡!