繁体   English   中英

如何使用 React 从数组中显示特定数量的项目

[英]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()在任意两个索引之间创建数组的浅表副本。 在实践中,您将使用它来制作从startArrayHerestartArrayHere + amountOfItemsToShow + 1的portfolioItems 的截断副本,并仅渲染这些项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM