[英]Curly braces inside curly braces in React
我在 React 中有展示組件。 使用products.some
我試圖檢查是否檢查了products
任何項目。 如果某個項目被選中,則為RequestedProduct
組件渲染父塊。 我知道問題是第二對花括號,因為 React 認為它是一個道具。 有沒有另一種方法可以做到這一點?
const Requested = ({ products, getCurrentTime }) => (
<div className="pepper-pin-body-tab requested-tab">
<div className="pepper-pin-body-tab-title">
Запрошенные
</div>
<div className="pepper-pin-body-tab-indicator" />
{products.some(product => product.checked) ? (
<div className="requested-tab-list-requested">
<div className="requested-tab-list-requested-time">
{getCurrentTime()}
</div>
{products.filter((product, key) => {
if (product.checked) {
return (
<RequestedProduct
key={key}
title={product.title}
/>
);
}
})}
</div>
) : null}
</div>
);
問題是, 過濾器不會返回自定義元素/值,它會始終返回您從過濾器主體返回 true 的數組元素。
解決方案是,僅使用地圖或過濾器和地圖的組合。
使用地圖:
{
products.map((product, key) => product.checked ?
<RequestedProduct key={key} title={product.title} />
: null
}
使用過濾器和地圖的組合:
{
products
.filter(product => product.checked)
.map((product, key) => <RequestedProduct key={key} title={product.title}/>)
}
檢查這個片段,你會得到一個更好的主意:
const arr = [ {a: 1}, {a: 2}, {a: 3}, {a: 4} ]; const afterFilter = arr.filter((el,i) => { if(i%2) { return `Hello world ${i}`; } }); // it will print the array items, not the Hello World string console.log('afterFilter', afterFilter);
我建議將代碼拆分一下,這使它的意圖更加清晰。 您最終會得到以下(例如),這不應觸發錯誤。
主要問題在於過濾器的意外副作用,而您很可能想要使用filter
和map
。 這使得另一個開發人員的意圖更加清晰。
const contents = (products, getCurrentTime) => (
const filtered = products.filter(product => product.checked);
<div className="requested-tab-list-requested">
<div className="requested-tab-list-requested-time">
{getCurrentTime()}
</div>
{filtered.map((product, key) => <RequestedProduct key={key} title={product.title}/>)}
</div>
);
const Requested = ({products, getCurrentTime}) => {
const isAnythingChecked = products.some(product => product.checked);
return <div className="pepper-pin-body-tab requested-tab">
<div className="pepper-pin-body-tab-title">
Запрошенные
</div>
<div className="pepper-pin-body-tab-indicator"/>
{isAnythingChecked ? contents(products, getCurrentTime) : null}
</div>
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.