Is it possible to map only a portion of an array? (Array.map())

前端 未结 8 964
终归单人心
终归单人心 2020-12-31 07:16

I am building a project using React.js as a front-end framework. On one particular page I am displaying a full data set to the user. I have an Array which contains this full

8条回答
  •  情歌与酒
    2020-12-31 07:38

    Do not try to solve this problem with a hack in your mapping step.

    Instead, slice() the list to the right length first before the mapping:

    class Feed extends React.Component {
      constructor(props) {
        super(props)
        
        this.handleShowMore = this.handleShowMore.bind(this)
        
        this.state = {
          items: ['Item A', 'Item B', 'Item C', 'Item D'],
          showItems: 2
        }
      }
      
      handleShowMore() {
        this.setState({
          showItems: 
            this.state.showItems >= this.state.items.length ?
              this.state.showItems : this.state.showItems + 1
        })
      }
      
      render() {
        const items = this.state.items.slice(0, this.state.showItems).map(
          (item) => 
    {item}
    ) return (
    {items}
    ) } } ReactDOM.render( , document.getElementById('root') )
    
    
    
    

提交回复
热议问题