react 高階用法

語言: CN / TW / HK

theme: channing-cyan highlight: night-owl


這是我參與11月更文挑戰的第24天,活動詳情檢視:[2021最後一次更文挑戰](http://juejin.cn/post/7023643374569816095/ "http://juejin.cn/post/7023643374569816095/") > TIP 👉 **英雄者,胸懷大志,腹有良策,有包藏宇宙之機,吞吐天地之志者也。——《三國演義》** ![image.png]()

前言

React高階元件 高階元件 高階函式的基本概念 - 函式可以作為引數被傳遞 - 函式可以作為返回值輸出 高階元件的基本概念 ![image.png](http://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6e70a44e6bbd469382a9d894d92f9e7e~tplv-k3u1fbpfcp-watermark.image?) 本質是利用一個函式,該函式接受react元件,並返回一個新的元件,一個元件經過一個函式以後成為了一個具有新的業務邏輯的元件 ```js const NewComponent = higherOrderComponent(oldComponent) ``` - 高階元件就是接受一個元件作為引數並返回一個新元件的函式 - 高階元件是一個函式,並不是元件 非同步元件 傳統模式:渲染元件-> 請求資料 -> 再渲染元件。 非同步模式:請求資料-> 渲染元件。 開啟Suspense模式 ```js function Index(){ const [ userInfo , setUserInfo ] = React.useState(0) React.useEffect(()=>{ /* 請求資料互動 */ getUserInfo().then(res=>{ setUserInfo(res) }) },[]) return

{userInfo.name}

;
} export default function Home(){ return
} ``` 模擬一個簡單的Suspense ```js export class Suspense extends React.Component{ state={ isRender: true } componentDidCatch(e){ /* 非同步請求中,渲染 fallback */ this.setState({ isRender:false }) const { p } = e Promise.resolve(p).then(()=>{ /* 資料請求後,渲染真實元件 */ this.setState({ isRender:true }) }) } render(){ const { isRender } = this.state const { children , fallback } = this.props return isRender ? children : fallback } } ``` React.lazy基本使用 ```js const LazyComponent = React.lazy(()=>import('./text')) ``` ```js const LazyComponent = React.lazy(() => import('./test.js')) export default function Index(){ return loading...

} > } ``` Suspense能解決什麼?

  • Suspense讓資料獲取庫與 React 緊密整合。如果一個數據請求庫實現了對 Suspense 的支援,那麼,在 React 中使用 Suspense 將會是自然不過的事。
  • Suspense能夠自由的展現,請求中的載入效果。能讓檢視載入有更主動的控制權。
  • Suspense能夠讓請求資料到渲染更流暢靈活,我們不用在componentDidMount請求資料,再次觸發render,一切交給Suspense解決,一氣呵成。

「歡迎在評論區討論」

希望看完的朋友可以給個贊,鼓勵一下