Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

javascript - How to display a specific amount of items from an array using React

Instead of showing every single item inside 'portfolioComponents', I want to show a specific amount of items, from a specific number ('startArrayHere') in the array, and raise and lower from which number ('startArrayHere') I start showing items from the Array. I know the For-Loop is wrong, but I just can't figure out how to do it - can anybody help me out here?

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get a subset of an Array in JS, use the .slice method

Array.slice(startIndexInclusive, endIndexExclusive)

Reference:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Example:

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

So, to incorporate your amountOfItems you'd have to just do

a.slice(startIndex, startIndex + amountOfItems)

I hope this helps somewhat.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...