![](/img/trans.png)
[英]Javascript: how to display certain amount of items from an array and display others on button click?
[英]How to display a specific amount of items from an array using React
我不想顯示“portfolioComponents”中的每個項目,而是從數組中的特定數字(“startArrayHere”)顯示特定數量的項目,並從哪個數字(“startArrayHere”)開始顯示項目從陣列。 我知道 For-Loop 是錯誤的,但我就是不知道該怎么做 - 有人可以幫我嗎?
class Portfolio extends Component {
constructor(){
super ()
this.state = {
portitems: portfolioItems,
startArrayHere: 0,
amountOfItemsToShow: 6
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
if(this.state.startArrayHere < (portfolioItems.length -
this.state.amountOfItemsToShow))
this.setState(prevState => {
return {
startArrayHere: startArrayHere + 1
}
})
}
render(){
const portfolioComponents = this.state.portitems.map(item =>
<PortfolioTemp key={item.id} portfolioitem={item} />)
return (
<div>
<button onClick={() => this.handleClick()}>STATE CHANGE</button>
<div className="portfolio-container">
{
for (let i = 0; i < this.state.amountOfItemsToShow; i++){
portfolioComponents[i + this.state.startArrayHere]
}
}
</div>
</div>
)
}
}
export default Portfolio;
要在 JS 中獲取 Array 的子集,請使用.slice
方法
Array.slice(startIndexInclusive, endIndexExclusive)
參考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
例子:
const a = ['Hello', 'World', 'Foo', 'Bar']
console.log(a.slice(0, 1)) // prints: ['Hello']
console.log(a.slice(0, 2)) // prints: ['Hello', 'World']
console.log(a.slice(2, a.length) // prints: ['Foo', 'Bar']
console.log(a.slice(0, a.length) // prints the entire array ... note: this would be pointless, as you could just print 'a' itself
所以,要合並你的amountOfItems
你必須做
a.slice(startIndex, startIndex + amountOfItems)
我希望這會有所幫助。
您可以使用Array.prototype.slice()在任意兩個索引之間創建數組的淺表副本。 在實踐中,您將使用它來制作從startArrayHere
到startArrayHere + amountOfItemsToShow + 1
的portfolioItems 的截斷副本,並僅渲染這些項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.