首頁 web前端 js教程 高級反應技術每個高級開發人員都應掌握

高級反應技術每個高級開發人員都應掌握

Jan 28, 2025 pm 02:33 PM

Advanced React Techniques Every Senior Developer Should Master

> React是用於製作用戶界面(尤其是單頁應用程序)的領先JavaScript庫,要求掌握高級技術來構建高效,可擴展和可維護的項目。 本文探討了高級開發人員的20個基本高級React概念,並用與您相關的打字稿示例進行了說明。

  1. 高階組件(HOCS):>
import React from 'react';

const withLogger = (WrappedComponent: React.ComponentType) => {
  return class extends React.Component {
    componentDidMount() {
      console.log(`Component ${WrappedComponent.name} mounted`);
    }
    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
};

const MyComponent: React.FC = () => <div>Hello World</div>;
const MyComponentWithLogger = withLogger(MyComponent);
    渲染props:
  1. >使用一個值為函數的prop之間的組件之間共享代碼。 >
>
import React from 'react';

interface DataFetcherProps {
  render: (data: any) => JSX.Element;
}

const DataFetcher: React.FC<DataFetcherProps> = ({ render }) => {
  const data = { name: 'John Doe' };
  return render(data);
};

const MyComponent: React.FC = () => (
  <DataFetcher render={(data) => <div>{data.name}</div>} />
);
上下文api:
    促進跨組件的數據共享,消除了道具鑽探。
import React, { createContext, useContext } from 'react';

const MyContext = createContext<string | null>(null);

const MyProvider: React.FC = ({ children }) => {
  const value = 'Hello from Context';
  return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
};

const MyComponent: React.FC = () => {
  const value = useContext(MyContext);
  return <div>{value}</div>;
};
自定義鉤子:
    封裝並重複使用狀態邏輯。
錯誤邊界:
import { useState, useEffect } from 'react';

const useFetch = (url: string) => {
  const [data, setData] = useState<any | null>(null);
  useEffect(() => {
    fetch(url)
      .then((response) => response.json())
      .then((data) => setData(data));
  }, [url]);
  return data;
};

const MyComponent: React.FC = () => {
  const data = useFetch('https://api.example.com/data');
  return <div>{data ? data.name : 'Loading...'}</div>;
};
捕獲並處理組件樹中的JavaScript錯誤。 >
  1. 代碼拆分:
>通過將代碼分成較小的塊來提高初始加載時間。 (webpack,lollup等)
import React from 'react';

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error: any) {
    return { hasError: true };
  }

  componentDidCatch(error: any, errorInfo: any) {
    console.error(error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

const MyComponent: React.FC = () => {
  throw new Error('Test error');
  return <div>Hello World</div>;
};

const App: React.FC = () => (
  <ErrorBoundary><MyComponent /></ErrorBoundary>
);
  1. >回憶(usememo):
通過緩存昂貴的計算來優化性能。
import React, { lazy, Suspense } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

const MyComponent: React.FC = () => (
  <Suspense fallback={<div>Loading...</div>}>
    <LazyComponent />
  </Suspense>
);
  1. 門戶:
>將孩子渲染到dom的另一部分。
import React, { useMemo } from 'react';

const MyComponent: React.FC = ({ items }) => {
  const sortedItems = useMemo(() => items.sort(), [items]);
  return <div>{sortedItems.join(', ')}</div>;
};
  1. 片段:
分組兒童而不添加額外的DOM節點。
import React from 'react';
import ReactDOM from 'react-dom';

const MyPortal: React.FC = () => {
  return ReactDOM.createPortal(
    <div>This is rendered in a portal</div>,
    document.getElementById('portal-root')!
  );
};
  1. refs和dom:
  2. 訪問dom節點或react元素。
import React from 'react';

const MyComponent: React.FC = () => (
  <React.Fragment>
    <div>Item 1</div>
    <div>Item 2</div>
  </React.Fragment>
);
  1. 轉發refs:
  2. >通過與孩子的組成部分的通過參考。
import React, { useRef, useEffect } from 'react';

const MyComponent: React.FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    inputRef.current?.focus();
  }, []);

  return <input ref={inputRef} />;
};
  1. 受控和不受控制的組件:
  2. >在外部或內部管理組件狀態。
>
import React, { forwardRef, useRef } from 'react';

const MyInput = forwardRef<HTMLInputElement>((props, ref) => (
  <input {...props} ref={ref} />
));

const MyComponent: React.FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);
  return <MyInput ref={inputRef} />;
};
  1. 性能優化(react.memo,usememo,usecallback):
防止不必要的重新租賃。
import React, { useState, useRef } from 'react';

const ControlledComponent: React.FC = () => {
  const [value, setValue] = useState('');
  return <input type="text" value={value} onChange={(e) => setValue(e.target.value)} />;
};

const UncontrolledComponent: React.FC = () => {
  const inputRef = useRef<HTMLInputElement>(null);
  return <input type="text" ref={inputRef} />;
};
  1. 服務器端渲染(SSR):在服務器上渲染組件以改進SEO和性能。 (需要諸如Next.js或Remix之類的服務器端框架。)
import React, { useCallback, memo } from 'react';

const MyComponent: React.FC<{ onClick: () => void }> = memo(({ onClick }) => {
  console.log('Rendering MyComponent');
  return <button onClick={onClick}>Click me</button>;
});

const ParentComponent: React.FC = () => {
  const handleClick = useCallback(() => {
    console.log('Button clicked');
  }, []);

  return <MyComponent onClick={handleClick} />;
};
  1. >

    >靜態站點生成(SSG):構建時間的預渲染頁面。 (next.js,gatsby等)

  2. >

    增量靜態再生(ISR):構建時間後更新靜態內容。 (next.js)

  3. >並發模式:

    提高響應能力並優雅地處理中斷。

import React from 'react';

const withLogger = (WrappedComponent: React.ComponentType) => {
  return class extends React.Component {
    componentDidMount() {
      console.log(`Component ${WrappedComponent.name} mounted`);
    }
    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
};

const MyComponent: React.FC = () => <div>Hello World</div>;
const MyComponentWithLogger = withLogger(MyComponent);
    用於數據獲取的
  1. > 懸念:在數據獲取過程中聲明處理加載狀態。
import React from 'react';

interface DataFetcherProps {
  render: (data: any) => JSX.Element;
}

const DataFetcher: React.FC<DataFetcherProps> = ({ render }) => {
  const data = { name: 'John Doe' };
  return render(data);
};

const MyComponent: React.FC = () => (
  <DataFetcher render={(data) => <div>{data.name}</div>} />
);
    >
  1. REACT查詢:簡化數據獲取,緩存和同步。
import React, { createContext, useContext } from 'react';

const MyContext = createContext<string | null>(null);

const MyProvider: React.FC = ({ children }) => {
  const value = 'Hello from Context';
  return <MyContext.Provider value={value}>{children}</MyContext.Provider>;
};

const MyComponent: React.FC = () => {
  const value = useContext(MyContext);
  return <div>{value}</div>;
};
>
    > React服務器組件:
  1. 結合客戶端交互與服務器端渲染好處。 (需要一個支持RSC的框架,例如Next.js 13。 >
  2. 結論:
掌握這些高級技術,使高級React開發人員能夠創建高性能,可維護和健壯的應用程序。 通過將這些策略集成到您的工作流程中,您將有能力處理複雜的項目並提供出色的用戶體驗。

以上是高級反應技術每個高級開發人員都應掌握的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

在打字稿中的高級條件類型 在打字稿中的高級條件類型 Aug 04, 2025 am 06:32 AM

TypeScript的高級條件類型通過TextendsU?X:Y語法實現類型間的邏輯判斷,其核心能力體現在分佈式條件類型、infer類型推斷和復雜類型工具的構建。 1.條件類型在裸類型參數上具有分佈性,能自動對聯合類型拆分處理,如ToArray得到string[]|number[]。 2.利用分佈性可構建過濾與提取工具:Exclude通過TextendsU?never:T排除類型,Extract通過TextendsU?T:never提取共性,NonNullable過濾null/undefined。 3

微觀前端體系結構:實施指南 微觀前端體系結構:實施指南 Aug 02, 2025 am 08:01 AM

Microfrontendssolvescalingchallengesinlargeteamsbyenablingindependentdevelopmentanddeployment.1)Chooseanintegrationstrategy:useModuleFederationinWebpack5forruntimeloadingandtrueindependence,build-timeintegrationforsimplesetups,oriframes/webcomponents

JavaScript中的VAR,LET和CONST之間有什麼區別? JavaScript中的VAR,LET和CONST之間有什麼區別? Aug 02, 2025 pm 01:30 PM

varisfunction-scoped,canbereassigned,hoistedwithundefined,andattachedtotheglobalwindowobject;2.letandconstareblock-scoped,withletallowingreassignmentandconstnotallowingit,thoughconstobjectscanhavemutableproperties;3.letandconstarehoistedbutnotinitial

生成可解的雙巧克力謎題:數據結構與算法指南 生成可解的雙巧克力謎題:數據結構與算法指南 Aug 05, 2025 am 08:30 AM

本文深入探討瞭如何為“雙巧克力”(Double-Choco)謎題遊戲自動生成可解謎題。我們將介紹一種高效的數據結構——基於2D網格的單元格對象,該對象包含邊界信息、顏色和狀態。在此基礎上,我們將詳細闡述一種遞歸的塊識別算法(類似於深度優先搜索),以及如何將其整合到迭代式謎題生成流程中,以確保生成的謎題滿足遊戲規則,並具備可解性。文章將提供示例代碼,並討論生成過程中的關鍵考量與優化策略。

如何使用JavaScript從DOM元素中刪除CSS類? 如何使用JavaScript從DOM元素中刪除CSS類? Aug 05, 2025 pm 12:51 PM

使用JavaScript從DOM元素中刪除CSS類最常用且推薦的方法是通過classList屬性的remove()方法。 1.使用element.classList.remove('className')可安全刪除單個或多個類,即使類不存在也不會報錯;2.替代方法是直接操作className屬性並通過字符串替換移除類,但易因正則匹配不准確或空格處理不當引發問題,因此不推薦;3.可通過element.classList.contains()先判斷類是否存在再刪除,但通常非必需;4.classList

JavaScript中的類語法是什麼?它與原型有何關係? JavaScript中的類語法是什麼?它與原型有何關係? Aug 03, 2025 pm 04:11 PM

JavaScript的class語法是原型繼承的語法糖,1.class定義的類本質是函數,方法添加到原型上;2.實例通過原型鏈查找方法;3.static方法屬於類本身;4.extends通過原型鏈實現繼承,底層仍使用prototype機制,class未改變JavaScript原型繼承的本質。

Vercel SPA路由與資源加載:解決深層URL訪問問題 Vercel SPA路由與資源加載:解決深層URL訪問問題 Aug 13, 2025 am 10:18 AM

本文旨在解決在Vercel上部署單頁應用(SPA)時,深層URL刷新或直接訪問導致頁面資源加載失敗的問題。核心在於理解Vercel的路由重寫機制與瀏覽器解析相對路徑的差異。通過配置vercel.json實現所有路徑重定向至index.html,並修正HTML中靜態資源的引用方式,將相對路徑改為絕對路徑,確保應用在任何URL下都能正確加載所有資源。

掌握JavaScript數組方法:``map`,`filt filter''和`reste'' 掌握JavaScript數組方法:``map`,`filt filter''和`reste'' Aug 03, 2025 am 05:54 AM

JavaScript的數組方法map、filter和reduce用於編寫清晰、函數式的代碼。 1.map用於轉換數組中的每個元素並返回新數組,如將攝氏溫度轉為華氏溫度;2.filter用於根據條件篩選元素並返回符合條件的新數組,如獲取偶數或活躍用戶;3.reduce用於累積結果,如求和或統計頻次,需提供初始值並返回累加器;三者均不修改原數組,可鍊式調用,適用於數據處理與轉換,提升代碼可讀性與功能性。

See all articles