gpt4 book ai didi

javascript - React 中循环内带有条件的切片方法

转载 作者:行者123 更新时间:2023-12-03 08:17:02 25 4
gpt4 key购买 nike

如果状态为 false,我想渲染 0 到 3 个项目,如果状态为 true,我想渲染 4 到数组长度的末尾,方法是单击查看更多

我有以下代码,但出现错误:

{items
.filter((item) => DateTime.fromISO(item.date).year === lastYear)
**.slice(showArticles ? (4, items.length) : (0, 3))**
.map((filteredItem) => (
<div>
<date>{filteredItem.date}</date>
<span>{filteredItem.article}</div>
</div>

))}
<button
onClick={() => {
showArticles;
}}
>
See more
</button>

当前切片条件正在实现,因此不会渲染任何内容。我怎样才能相应地展示我的元素?

最佳答案

您可以将参数数组传播到 slice 方法中。请记住,结束索引被排除,因此如果您想要元素 0-3,请指定 slice(0, 4)

Array.prototype.slice

The slice() method returns a shallow copy of a portion of an arrayinto a new array object selected from start to end (end not included)where start and end represent the index of items in that array. Theoriginal array will not be modified.

items.filter((item) => DateTime.fromISO(item.date).year === lastYear)
.slice(...(showArticles ? [4] : [0, 4])) // 4 through the end, or 0 to 3
.map((filteredItem) => (....

function App() {
const [showArticles, setShowArticles] = React.useState();

return (
<div className="App">
<button type="button" onClick={() => setShowArticles((s) => !s)}>
Toggle
</button>

{Array.from({ length: 10 }, (_, i) => i)
.slice(...(showArticles ? [4] : [0, 4]))
.map((el) => (
<li key={el}>{el}</li>
))}
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(
<App />,
rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />

关于javascript - React 中循环内带有条件的切片方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69040575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com