增強 React 列表渲染:乾淨且可重用的模式

aow054發表於2024-09-22
作為 react 開發人員,我們都遇到過需要渲染資料列表的場景。雖然 .map() 方法效果很好,但每次渲染列表時重複相同的邏輯可能會讓人筋疲力盡,並導致程式碼重複。幸運的是,有一種更乾淨、可擴充套件的方法來處理這個問題,使用可重用元件、高階元件或自定義掛鉤。在本文中,我將分享一種改進 react 中列表渲染的方法,確保您的程式碼保持 dry、可重用且更易於維護。 主要問題:重複的.map()邏輯假設您正在為電子商務應用程式構建儀表板。儀表板包含多個列表:最近訂單、最暢銷產品、使用者評論等。您需要使用 .map() 函式呈現每個列表。這是一個典型的例子:const orders = [...]; // array of order datareturn ( {orders.map((order, index) =&gt; ( <ordercomponent key="{index}" data="{order}"></ordercomponent> ))} &gt;);登入後複製現在,您可以看到每個列表都重複 .map() 邏輯,類似的程式碼使您的元件變得混亂。這就是可重複使用的模式可以派上用場的地方。 解決方案:可重用的listcomponent為了避免重複 .map() 邏輯,我們可以建立一個可重用的 listcomponent 來抽象對映邏輯,並允許我們根據資料渲染不同的元件。function listcomponent({ data, renderitem }) { return ( {data.map((item, index) =&gt; renderitem(item, index))} &gt; );}登入後複製用法:<listcomponent data="{orders}" renderitem="{(order," index> ( <ordercomponent key="{index}" data="{order}"></ordercomponent> )} /&gt;</listcomponent>登入後複製登入後複製在此模式中:renderitem:定義每個專案應如何渲染的函式透過傳遞不同的 renderitem 函式,我們可以為任何列表重用 listcomponent。這會產生一個乾淨、可重用的元件,減少重複的 .map() 邏輯。 更靈活:高階元件(hoc)如果多個元件需要列表渲染,讓我們透過建立一個高階元件進一步採用此模式。 hoc 允許透過附加功能增強任何元件 - 在本例中為列表渲染。function withlistrendering(wrappedcomponent) { return function listwrapper({ data, ...props }) { return ( {data.map((item, index) =&gt; ( <wrappedcomponent key="{index}" data="{item}"></wrappedcomponent> ))} &gt; ); };}登入後複製用法:const enhancedordercomponent = withlistrendering(ordercomponent);// now render the component with any data array<enhancedordercomponent data="{orders}"></enhancedordercomponent>登入後複製透過使用 withlistrendering hoc 包裝 ordercomponent,我們自動新增了列表渲染行為,而無需修改原始元件。這種模式使程式碼保持模組化。 對於 hook 愛好者:用於列表渲染的自定義 hookreact hooks 提供了一種封裝邏輯的函式式方法。如果您更喜歡使用鉤子,這裡是使用自定義鉤子渲染列表的示例。function uselistrenderer(data, renderitem) { return data.map((item, index) =&gt; renderitem(item, index));}登入後複製用法:function ordersdashboard({ orders }) { const orderlist = uselistrenderer(orders, (order, index) =&gt; ( <ordercomponent key="{index}" data="{order}"></ordercomponent> )); return {orderlist}&gt;;}登入後複製這種方法將 .map() 邏輯移動到鉤子中,使渲染邏輯與元件的結構分開。這是保持元件精簡併專注於演示的另一種方法。 現實場景:電子商務儀表板讓我們將此模式應用到現實場景中。想象一下,您正在構建一個電子商務管理儀表板,其中需要呈現多個訂單、產品、評論等列表。使用 listcomponent 方法,您可以呈現如下所示的訂單列表:<listcomponent data="{orders}" renderitem="{(order," index> ( <ordercomponent key="{index}" data="{order}"></ordercomponent> )} /&gt;</listcomponent>登入後複製登入後複製當我們需要渲染不同的列表(例如產品)時,可以透過不同的 renderitem 函式重用相同的 listcomponent:<listcomponent data="{products}" renderitem="{(product," index> ( <productcomponent key="{index}" data="{product}"></productcomponent> )} /&gt;</listcomponent>登入後複製無需重寫 .map() 邏輯 - 只需使用不同的資料和元件重用 listcomponent 即可。這使得程式碼庫在增長時更易於維護。 結論:乾淨、可重用且可擴充套件的程式碼可重用的 listcomponent 模式透過抽象重複的 .map() 邏輯來簡化 react 列表渲染。無論您喜歡使用基本元件方法、hoc 還是自定義掛鉤,此模式都可確保程式碼乾淨且可重用。構建具有多個列表的 react 元件,請考慮使用其中一種模式來使元件專注於表示,同時將列表邏輯分離出來。您發現 react 中還有哪些其他有用的可重用模式?請在評論中告訴我! 最後感謝您的閱讀 以上就是增強 React 列表渲染:乾淨且可重用的模式的詳細內容,更多請關注我的其它相關文章!

相關文章