我在反應組件中有以下邏輯,我根據布林值呈現不同的組件。這種和平的代碼很難理解。無論如何,我可以簡單地說邏輯:
{isEnabled ? (
<>
{!loading ? (
<>
{items.length === 0 ? (
<>
<ComponentOne/>
<Container>
<img src={Image} alt="Image" />
</Container>
</>
) : (
<ComponentTwo/>
)}
</>
) : (
<div>
<LoadingComponent/>
</div>
)}
</>
) : (
<ComponentThree/>
)}
uj5u.com熱心網友回復:
例如,我可能會將其拆分為單獨的組件并沿組件樹向下傳遞引數
{isEnabled ? <IsLoadingComponent loading={loading} items={items}> : <ComponentThree/>}
uj5u.com熱心網友回復:
您可能會發現將組件拆分為“正在加載”版本和“已加載”版本很有用,這樣您就不必在同一個組件中處理這兩種狀態。然后組件基本上只是根據標志呈現“加載”或“加載”版本。
但即使沒有它,您至少可以通過使用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}
嵌套條件在哪里。
uj5u.com熱心網友回復:
我認為你把一件簡單的事情變得非常復雜。我們可以做的是利用“&&”。
{ isEnabled && loading && <LoaderComponent /> }
{isEnabled && !items.length &&
<>
<ComponentOne/>
<Container>
<img src={Image} alt="Image" />
</Container>
</>
}
{isEnabled && items.length && <ComponentTwo/>}
{!isEnabled && <ComponentThree />}
uj5u.com熱心網友回復:
盡管我想支持其他人提出的論點(分為多個部分),但您已經可以通過洗掉不必要的片段 ( <></>) 和/或括號并使用“更好” (意見)縮進來提高可讀性。
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>
</>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/339830.html
標籤:javascript 反应 条件运算符
