[英]How to remove elements in an array based on their odd or even index?
我正在嘗試通過奇數和偶數索引對數組進行排序,然后通過將其作為prop傳遞給另一個組件來顯示其數據。
讓我解釋一下我的工作原理:
我有一個名為products(woocommerce data)的數組。
const products = [
{ attributes: [{ option: "size 1" }] },
{ attributes: [{ option: "size 2" }] },
{ attributes: [{ option: "size 3" }] }
];
我已經設置了一個.map()
函數,對於我的數組中的每個對象,我將返回一個這樣的組件;
let sizeVariations = products.map((product, index) => {
return (
<div key={index}>
<Buttons
sizeEven={product.attributes[0].option}
sizeOdd={product.attributes[0].option}
/>
</div>
);
});
我想通過這個組件傳遞大小作為兩個不同的道具sizeEven
和sizeOdd
,它們等於product.attributes[0].option
。
但是對於product.attributes[0].option
我想為每個道具“彈出”或過濾掉所有奇數或偶數索引。
我該怎么做呢?
目前我有這種格式( https://codesandbox.io/s/018488478p )不起作用,因為你只能在evenArray
或oddArray
傳遞一個索引。
我不知道你想怎么做,但實際上你不需要創建額外的數組。 我對CSS不太滿意,但在這里我是如何用四個元素做的。 最后一個將以三個元素為中心。 至少功能有效,但我不確定CSS。
更新
我已經改變了一點代碼。 我將Buttons
組件定義為功能組件而不是類。 實際上, App
也會是這樣,但未來會有一些狀態。 我將地圖操作移動到一個單獨的函數中並將其移動到return
之外。 所以我們在return
方法中有一個更清晰的邏輯。
注意:請勿使用我在此處使用的key
索引。 使用其他一些unqiue值。
看到這里 。
如果項目的順序可能發生變化,我們不建議使用密鑰索引。 這可能會對性能產生負面影響,並可能導致組件狀態出現問題。 查看Robin Pokorny的文章,深入解釋使用索引作為關鍵的負面影響。 如果您選擇不為列表項分配顯式鍵,則React將默認使用索引作為鍵。
這里有一個深入的解釋,如果您有興趣了解更多信息,為什么需要密鑰。
此外,如果React版本足夠新,我們可以使用top <React.Fragment>
並使用一個鍵。
const Buttons = props => { const { products } = props; const renderOptions = () => products.map((p, i) => !( i % 2 ) ? <div key={i} className="left">{p.attributes[0].option}</div> : <div key={i} className="right">{p.attributes[0].option}</div> ); return <div className="container">{renderOptions()}</div>; }; class App extends React.Component { render() { const products = [ { attributes: [{ option: "size 1" }] }, { attributes: [{ option: "size 2" }] }, { attributes: [{ option: "size 3" }] }, { attributes: [{ option: "size 4" }] }, ]; return ( <div className="App"> <Buttons products={products} /> </div> ); } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
.container { width: 300px; height: 50px; padding-bottom: 10px; margin: 0 auto; } .left { width: 100px; height: 50px; margin: 0 20px 20px 0; border: 1px solid red; display: inline-block; } .right { width: 100px; height: 50px; border: 1px solid blue; display: inline-block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
const products = [
{ attributes: [{ option: "size 1" }] },
{ attributes: [{ option: "size 2" }] },
{ attributes: [{ option: "size 3" }] }
];
const evenArray = products.filter((product, index) => index % 2 )
我們可以使用Array.filter方法創建一個新數組,其中的元素通過我們提供的測試(product, index) => index % 2
,在這種情況下:如果我們的元素索引可以被2整除。我們可以通過使用模數運算符找到它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.