[英]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.