React 條件渲染最佳實踐小結(7種)
在 React 中,條件渲染可以通過多種方式,不同的使用方式場景取決于不同的上下文。 在本文中,我們將討論所有可用于為 React 中的條件渲染編寫更好的代碼的方法。
條件渲染在每種編程語言(包括 javascript)中都是的常見功能。 在 javascript 中,我們通常使用if else 語句,switch case語句和三元運算符編寫條件渲染。
以上所有這些方法都適用于 React。 但是問題是,我們如何才能有效地使用它們?
像你知道的那樣,React 具有 JSX 標記,通常我們需要實現(xiàn)條件邏輯去控制組件。 但是,我們不能在 JSX 中直接使用常見的 if else或switch case語句。
在 JSX 中,我們應該使用其他條件渲染方法,例如三元運算符和&&運算符。 在這里,我們將討論更多細節(jié)。
以下是我積累的 7 種條件渲染方法,它們可以在 React 中使用。 每種方式在一定的情況下都有自己的優(yōu)勢。
目錄
- If Else條件渲染
- 使用三元運算符進行條件渲染
- &&運算符的條件渲染
- 帶switch case多條件渲染
- 枚舉對象的多條件渲染
- HOC(高階組件)條件渲染
- 帶有外部庫的 JSX 條件渲染
1.If Else條件渲染
最佳實踐概述
- 在 JSX 標記之外的任何地方使用
- 或者,如果你想在 if-else 塊中執(zhí)行多行代碼
這是所有程序員都能想到的第一個方法,即常見的 if-else語句。 我們可以在 React 項目中的任何地方使用它。
在 React 中,如果要在 if 或者 else 塊內部或 JSX 外部的任何地方執(zhí)行多行代碼,最好使用通用的 if-else 語句。
例如,如果用戶登錄,我們想執(zhí)行一些代碼。
// * Conditional rendering with common if-else statement. if (isLoggedIn) { setUserProfile(userData); setUserHistory(userHistory); // other block of codes; }
或者,當你想基于用戶角色定義可訪問的內容時。
if (userProfile.role === "superadmin") { initSuperAdminFunction(); initSuperAdminComponent(); // other block of codes; } else if (userProfile.role === "admin") { initAdminFunction(); initAdminComponent(); // other block of codes; } else { initUserComponent(); // other block of codes; }
如果你只想執(zhí)行一行代碼,例如在 if 或 else 塊中調用函數(shù),則可以刪除括號。
if (userProfile.role === "superadmin") initSuperAdminComponent(); else if (userProfile.role === "admin") initAdminFunction(); else initUserComponent();
if-else 中不帶括號的條件僅適用于其正下方的一行代碼。
JSX 中的 if else 語句
你可能知道,我們可以在 JSX 中的方括號{}中注入和混合一些 javascript 代碼。 但是它有一些局限性。
你不能直接向其中插入 if-else 語句。 在 JSX 中注入 if-else 語句僅適用于立即調用函數(shù)表達式(IIFE),如下所示:
return ( <div> {(() => { if (isLoggedIn) { return <div>I'm logged in.</div>; } })()} </div> );
如你所見,僅 if 語句就太冗長了。 這就是為什么我不建議在 JSX 中使用 if-else 語句的原因。
繼續(xù)閱讀 JSX 中還有其他一些條件渲染的方法。
2.使用三元運算符進行條件渲染
最佳實踐概覽
- 條件變量或函數(shù)返回值賦值
- 當你只想寫一行代碼來做條件判斷
- 于 JSX 中的條件渲染
三元運算符是常見 if-else 語句的快捷方式。 使用三元運算符,你可以在行內編寫條件渲染,也可以只編寫一行代碼。
讓我們看一下條件渲染的變量值分配示例。
// Conditional rendering with common if else let isDrinkCoffee; if (role === "programmer") { isDrinkCoffee = true; } else { isDrinkCoffee = false; } // Conditional rendering with ternary operator let isDrinkCoffee = role === "programmer" ? true : false;
這是函數(shù)返回值的條件渲染示例:
// Conditional rendering with common if else function isDrinkCoffee(role) { if (role === "programmer") { return true; } else { return false; } } // Conditional rendering with ternary operator function isDrinkCoffee(role) { return role === "programmer" ? true : false; }
如你所見, 你用了三元運算符,就用用一行代碼來代替 if-else 語句。
你也可以在 JSX 中使用三元運算符,而不是將 if-else 與立即調用函數(shù)表達式(IIFE)一起使用。
假設我們要基于 isShow 狀態(tài)有條件地渲染一個小組件。 您可以這樣編寫條件渲染。
return <div>{isShow ? <SmallComponent /> : null}</div>;
if-else if-else使用三元運算符
在上面的示例中,我僅向你展示如何使用三元運算符替換 if-else 語句。
三元運算符還可用于替換多個條件渲染(if-else if-else)或嵌套的條件渲染。
但是,我不建議你使用它,因為它比普通的 if-else語句更難讀。
假設你要在 JSX 中實現(xiàn)嵌套的條件渲染。
return ( <div> {condition_a ? ( <ComponentA /> ) : condition_b ? ( <ComponentB /> ) : condition_c ? ( <ComponentC /> ) : ( <ComponentD /> )} </div> );
看起來非常亂,是吧?
對于這種情況,使用 IIFE,switch-case 語句或枚舉對象比三元運算符更好。
3.&&運算符的條件渲染
最佳實踐概覽
- 使用它進行簡單的條件渲染,不必去執(zhí)行"else"塊中的代碼。
使用三元運算符,可以縮短 if-else 語句的代碼量,并為 JSX 中的條件渲染提供更好的選擇。
但是,你知道有比三元運算符更簡單的方法嗎?
&&運算符可用于替換此類 if 語句。
// Instead of using ternary operator, { isShow ? <SmallComponent /> : null; } // Use short-circuit && operator { isShow && <SmallComponent />; }
在三元運算符中,即使沒有"else"條件,也需要寫"null"表達式以避免語法錯誤。
使用&&運算符,你不需要寫多余的代碼。
但是,請記住,不能將&&運算符替換為if-else語句,更不用說if-else if-else語句了。
4.帶 switch 的多條件渲染-案例
可以在任何位置使用它來進行多個條件渲染,而只有一個變量可以判斷條件。
像if-else語句一樣,switch-case語句也是幾乎每種編程語言中的常見功能。
它用于具有相同類型條件的多個條件渲染。
例如,我們可以使用switch-case語句根據(jù)用戶角色呈現(xiàn)特定的變量值。
let welcomeMessage; switch (role) { case "superadmin": welcomeMessage = "Welcome Super Admin"; // you can put other codes here as well. case "admin": welcomeMessage = "Welcome Admin"; // you can put other codes here as well. case "user": welcomeMessage = "Welcome User"; // you can put other codes here as well. default: welcomeMessage = "Welcome Guest"; // you can put other codes here as well. }
你還可以使用switch-case語句在 JSX 中進行條件渲染。 但是,你需要將其包裝在 IIFE 中。
假設你要呈現(xiàn)一個基于 alert 狀態(tài)設置樣式的alert組件。
return ( <div> {(() => { switch (status) { case "warning": return <AlertComponent status="warning" message={messageState} />; case "error": return <AlertComponent status="error" message={messageState} />; case "success": return <AlertComponent status="success" message={messageState} />; default: return <AlertComponent status="info" message={messageState} />; } })()} </div> );
你可能已經(jīng)注意到,兩個示例都只有一個變量(role和status)來判斷條件。 這就是我之前所說的相同類型的條件。
switch-case語句不能用于處理復雜和不同類型的條件。但是你可以使用通用的if-else if-else語句去處理那些場景。
5.枚舉對象的多重條件渲染
僅當您要分配具有多個條件的變量值或返回值時,才使用它。
枚舉對象還可以用于在 React 中實現(xiàn)多個條件渲染。 對于 JSX 標記中的 switch-case語句,它是更好的選擇。
如你所知,在第 5 種方法中,你應該將switch-case語句包裝在 JSX 的 IIFE 中。 使用枚舉對象,你不需要這樣做。
讓我們用一個以前的一個示例來距離。 你要基于狀態(tài)呈現(xiàn) alert 組件。 這是使用枚舉對象有條件地呈現(xiàn)它的方式。
const ALERT_STATUS = { warning: <AlertComponent status="warning" />, error: <AlertComponent status="error" />, success: <AlertComponent status="success" />, info: <AlertComponent status="info" />, }; return <div>{ALERT_STATUS[status]}</div>;
你需要創(chuàng)建一個枚舉對象,首先稱為“ ALERT_STATUS”。 然后,只需在 JSX 中使用 []括號內的狀態(tài)變量來調用它,該變量的值為'warning','error','success'或'info'。
如果需要傳遞其他道具或屬性,則可以將 ALERT_STATUS 更改為這樣的函數(shù)。
const ALERT_STATUS = (message) => ({ warning: <AlertComponent status="warning" message={message} />, error: <AlertComponent status="error" message={message} />, success: <AlertComponent status="success" message={message} />, info: <AlertComponent status="info" message={message} />, }); return <div>{ALERT_STATUS(messageState)[status]}</div>;
你還可以將變量傳遞給 alert 組件。
let newVariable = ALERT_STATUS(messageState)[status];
當然,你應該首先定義枚舉對象。
將枚舉對象拆分到單獨文件來復用
關于使用枚舉對象進行條件渲染的最好的特性是可以復用。
回到示例案例,Alert 組件是 React 中通??芍赜玫慕M件。 因此,當你要有條件地渲染它時,也可以讓它復用。
你可以在單獨的文件中定義枚舉,然后將它導出。
import React from "react"; import AlertComponent from "./path/to/AlertComponent"; export const ALERT_STATUS = (message) => ({ warning: <AlertComponent status="warning" message={message} />, error: <AlertComponent status="error" message={message} />, success: <AlertComponent status="success" message={message} />, info: <AlertComponent status="info" message={message} />, });
然后,在要在組件中使用它時將其導入。
import { ALERT_STATUS } from "./alertStatus";
用法與以前相同。
6.HOC 條件渲染
最佳做法摘要
如果要在渲染組件之前實現(xiàn)或檢查某些條件,請使用它。
高階組件(HOC)可用于在 React 中實現(xiàn)條件渲染。 當你要運行某些邏輯或在渲染組件之前進行檢查時,可以使用它。
例如,你要在訪問某些組件之前檢查用戶是否已通過身份驗證。
你可以使用 HOC 來保護那些組件,而不是在每個需要身份驗證的組件中編寫if-else語句。
// This is Higher Order Component import React from "react"; export default function withAuthentication(Component) { // some code of authentication logic/service that result an isLoggedIn variable/state: let isLoggedIn = true; return function AuthenticatedComponent(props) { if (isLoggedIn) { return <Component {...props} />; } else { return <div class="alert alert-danger">You're not authenticated!</div>; } }; }
然后,您可以將其導入并在組件中使用。
import withAuthentication from "./withAuthentication"; const AuthenticatedUIComponent = withAuthentication(AnUIComponent); return ( <div> <AuthenticatedUIComponent /> </div> );
這樣更棒了,是嗎?
你可以將 HOC 用于其他可復用的條件渲染,例如加載指示器實現(xiàn),空值檢查 等。
有關 HOC(具有功能組件)的更多詳細信息,可以在 medium (https://medium.com/@albertchu539/higher-order-components-in-a-react-hooks-world-69fe1f0b0791)。
7.帶有外部庫的 JSX 條件渲染
最佳做法摘要
- 避免使用此方法。 熟悉上面的 6 種方法:D
盡管我不建議你使用此方法,但我只是想讓你知道,有一個 babel 插件使 JSX 具有自己的條件渲染標記。
使用 JSX 控制語句,您可以像這樣在 JSX 中編寫條件渲染。
<If condition={test}> <span>Truth</span> </If>; <Choose> <When condition={test1}> <span>IfBlock</span> </When> <When condition={test2}> <span>ElseIfBlock</span> <span>Another ElseIfBlock</span> <span>...</span> </When> <Otherwise> <span>ElseBlock</span> </Otherwise> </Choose>;
在編譯中,這些標簽將轉換為三元運算符。
一些開發(fā)人員使用此插件,因為它對于 JSX 中的條件渲染看起來更具可讀性。
譯者注: 你還可以實現(xiàn)一個簡單的 IF 組件來實現(xiàn)簡單的判斷。
const If = (props) => { const condition = props.condition || false; const positive = props.then || null; const negative = props.else || null; return condition ? positive : negative; };
<IF condition={isLoggedIn} then={<Hello />} else={<div>請先登錄</div>} />
這就是你可以在 React 中用于條件渲染的所有 7 種方法。
編碼愉快!
譯文來自 https://dev.to/syakirurahman/react-conditional-rendering-best-practices-with-7-different-methods-16e3#6_Conditional_Rendering_with_HOC
原作者 Syakir Rahman譯者: 藍色的秋風(github/hua1995116)
到此這篇關于React 條件渲染最佳實踐小結(7種)的文章就介紹到這了,更多相關React 條件渲染內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
react性能優(yōu)化達到最大化的方法 immutable.js使用的必要性
這篇文章主要為大家詳細介紹了react性能優(yōu)化達到最大化的方法,一步一步優(yōu)化react性能的過程,告訴大家使用immutable.js的必要性,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03Taro?React自定義TabBar使用useContext解決底部選中異常
這篇文章主要為大家介紹了Taro?React底部自定義TabBar使用React?useContext解決底部選中異常(需要點兩次才能選中的問題)示例詳解,有需要的朋友可以借鑒參考下2023-08-08react echarts tooltip 區(qū)域新加輸入框編輯保存數(shù)據(jù)功能
這篇文章主要介紹了react echarts tooltip 區(qū)域新加輸入框編輯保存數(shù)據(jù)功能,大概思路是用一個div包裹echarts, 然后在echarts的同級新建一個div用來用來模擬真實tooltip,通過鼠標移入移出事件控制真實tooltip的顯示與隱藏,需要的朋友可以參考下2023-05-05React useImperativeHandle處理組件狀態(tài)和生命周期用法詳解
React Hooks 為我們提供了一種全新的方式來處理組件的狀態(tài)和生命周期,useImperativeHandle是一個相對較少被提及的Hook,但在某些場景下,它是非常有用的,本文將深討useImperativeHandle的用法,并通過實例來加深理解2023-09-09