React 소스 코드의 queueMacroTask

Linda Hamilton
풀어 주다: 2024-10-03 06:41:01
원래의
190명이 탐색했습니다.

이 글에서는 React 소스 코드의 queueMacroTask를 분석합니다.

queueMacroTask in React source code

파일과 함수의 이름은 enqueueTask로 되어 있지만 import는 queueMacroTask로 가져옵니다. window.queueMicroTask와 달리 window.queueMarcoTask와 같은 기능은 없습니다. setTimeout은 MacroTask의 예입니다.

이벤트 루프, 마이크로 태스크, 매크로 태스크에 대해 자세히 알아보세요.

React의 enqueueTask:

/**
 * Copyright © Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */
let didWarnAboutMessageChannel = false;
let enqueueTaskImpl = null;
export default function enqueueTask(task: () => void): void {
   if (enqueueTaskImpl === null) {
     try {
       // read require off the module object to get around the bundlers.
       // we don't want them to detect a require and bundle a Node polyfill.
       const requireString = ('require' + Math.random()).slice(0, 7);
       // $FlowFixMe[invalid-computed-prop]
       const nodeRequire = module && module[requireString];
       // assuming we're in node, let's try to get node's
       // version of setImmediate, bypassing fake timers if any.
       enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate;
       } catch (_err) {
       // we're in a browser
       // we can't use regular timers because they may still be faked
       // so we try MessageChannel+postMessage instead
       enqueueTaskImpl = function (callback: () => void) {
       if (__DEV__) {
         if (didWarnAboutMessageChannel === false) {
           didWarnAboutMessageChannel = true;
           if (typeof MessageChannel === 'undefined') {
             console.error(
             'This browser does not have a MessageChannel implementation, ' +
             'so enqueuing tasks via await act(async () => …) will fail. ' +
             'Please file an issue at https://github.com/facebook/react/issues ' +
             'if you encounter this warning.',
             );
           }
         }
       }
       const channel = new MessageChannel();
       channel.port1.onmessage = callback;
       channel.port2.postMessage(undefined);
     };
   }
  }
  return enqueueTaskImpl(task);
}
로그인 후 복사

이 코드에는 해당 코드의 기능을 설명하는 주석이 있습니다. 여기에서 배울 수 있는 몇 가지 요령이 있습니다.

  • 자신만의 enqueque trask를 작성할 때 번들러를 피하는 방법.

  • 노드 환경에서는 setImmediate를 MacroTask로 사용할 수 있습니다.

  • 브라우저 환경에서 MessageChannel을 사용하여 queueMacroTask 효과를 생성할 수 있습니다.

이 enquequeTask는 ReactAct.js에서 MacroTask로 가져오며 window.queueMicroTask가 존재하지 않는 경우 대체 수단으로 사용됩니다.

queueMacroTask in React source code

다음 줄:

  • https://github.com/facebook/react/blob/5d19e1c8d1a6c0b5cd7532d43b707191eaf105b7/packages/react/src/ReactAct.js#L196

  • https://github.com/facebook/react/blob/5d19e1c8d1a6c0b5cd7532d43b707191eaf105b7/packages/react/src/ReactAct.js#L121

회사 소개:

Think Throo에서는 오픈 소스 프로젝트에 사용되는 고급 코드베이스 아키텍처 개념을 가르치는 임무를 수행하고 있습니다.

Next.js/React에서 고급 아키텍처 개념을 연습하여 코딩 기술을 10배, 모범 사례를 배우고 프로덕션급 프로젝트를 구축하세요.

저희는 오픈 소스입니다 — https://github.com/thinkthroo/thinkthroo(별표를 주세요!)

코드베이스 아키텍처를 기반으로 한 고급 과정을 통해 팀의 기술을 향상하세요. 자세한 내용은 hello@thinkthroo.com으로 문의하세요!

참고자료

  • https://github.com/facebook/react/blob/5d19e1c8d1a6c0b5cd7532d43b707191eaf105b7/packages/react/src/ReactAct.js#L366

  • https://github.com/facebook/react/blob/5d19e1c8d1a6c0b5cd7532d43b707191eaf105b7/packages/shared/enqueueTask.js

    3. https://javascript.info/event-loop



위 내용은 React 소스 코드의 queueMacroTask의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!