[英]How to simply nested ternary logic in react while rendering different component
我在反應組件中有以下邏輯,我根據布爾值呈現不同的組件。 這種和平的代碼很難理解。 無論如何,我可以簡單地說邏輯:
{isEnabled ? (
<>
{!loading ? (
<>
{items.length === 0 ? (
<>
<ComponentOne/>
<Container>
<img src={Image} alt="Image" />
</Container>
</>
) : (
<ComponentTwo/>
)}
</>
) : (
<div>
<LoadingComponent/>
</div>
)}
</>
) : (
<ComponentThree/>
)}
例如,我可能會將其拆分為單獨的組件並沿組件樹向下傳遞參數
{isEnabled ? <IsLoadingComponent loading={loading} items={items}> : <ComponentThree/>}
您可能會發現將組件拆分為“正在加載”版本和“已加載”版本很有用,這樣您就不必在同一個組件中處理這兩種狀態。 然后組件基本上只是根據標志呈現“加載”或“加載”版本。
但即使沒有,您至少可以通過使用if
/ else if
等並分配給臨時變量來使調試更容易:
let comp;
if (isEnabled) {
if (loading) {
comp = <div>
<LoadingComponent/>
</div>;
} else if (items.length === 0) {
comp = <>
<ComponentOne/>
<Container>
<img src={Image} alt="Image" />
</Container>
</>;
} else {
comp = <ComponentTwo />;
}
} else {
comp = <ComponentThree />;
}
那么就
{comp}
嵌套條件在哪里。
我認為你把一件簡單的事情變得非常復雜。 我們可以做的是利用“&&”。
{ isEnabled && loading && <LoaderComponent /> }
{isEnabled && !items.length &&
<>
<ComponentOne/>
<Container>
<img src={Image} alt="Image" />
</Container>
</>
}
{isEnabled && items.length && <ComponentTwo/>}
{!isEnabled && <ComponentThree />}
盡管我想支持其他人提出的論點(分為多個部分),但您已經可以通過刪除不必要的片段( <></>
)和/或括號並使用“更好” (意見)縮進來提高可讀性.
return (
isEnabled
? loading
? <div><LoadingComponent/></div>
: items.length === 0
? <> {/* this is the only place a fragment is actually needed */}
<ComponentOne/>
<Container>
<img src={Image} alt="Image"/>
</Container>
</>
: <ComponentTwo/>
: <ComponentThree/>
);
或者,早期返回對可讀性有很大幫助。 例如:
const SomeComponent = () => {
// ...snip...
if (!isEnabled) {
return <ComponentThree/>;
}
if (loading) {
return <div><LoadingComponent/></div>;
}
if (items.length > 0) {
return <ComponentThree/>;
}
return (
<>
<ComponentOne/>
<Container>
<img src={Image} alt="Image"/>
</Container>
</>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.