关于React暂挂和并发模式

发布于:2021-02-17 00:00:20

0

87

0

react javascript webdev

React路线图上的下一个大事是并发模式和悬念模式,它们是相互关联、相辅相成的,所以人们有时会把它们混在一起。但它们代表着截然不同的概念。

并发模式

 

要理解并发模式,请考虑优先级。

如果没有并发模式,当React开始渲染某个东西时,它会一直渲染它,直到它完成为止。

在并发模式下,React会关注其他需要完成的事情,如果有更高优先级的事情,它会暂停呈现的内容,让其他事情先完成。“另一件事”可能是:

  • 浏览器需要执行的操作

  • 另一个React更新需要呈现

  • 来自其他库或应用程序代码的任何其他任务

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

您不需要为每个更新显式地设置优先级,如果您没有反应,您将尝试猜测正确的更新。

悬念

对于悬念,想想等待。

毫无疑问,如果组件需要等待任何依赖项(例如,如果它依赖于需要从服务器获取的某些数据),则需要添加一些状态来跟踪挂起的依赖项,在依赖项挂起时呈现某些内容,并在依赖项就绪时更新状态。

有了悬念,您的组件将能够告诉React“嘿React,我没有所有需要渲染的东西,但是我会告诉您什么时候您可以再次尝试渲染我”。您的组件不需要保持额外的状态,也不需要在等待时决定渲染什么。

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候机楼等我的航班延误,看着墙壁上的画,写了这一篇文章。希望大家能喜欢!