从数组动态加载React组件的子集

时间:2018-03-22 20:33:48

标签: javascript arrays reactjs components

我有一个React组件ItemsContainer,我想在其中呈现一组Items(每个都在一个新行中)。 ItemsContainer接收两个道具items,它是应该呈现的Item组件的数组,numberOfItems是一个数字,表示我想要一次呈现多少项。每个项目都有一个解除按钮,该按钮应该使当前项目消失并使容器中的其他项目向上移动,并显示items中的下一个项目(与在社交媒体网站上解除通知的流程相同)。我弄清楚了: 1.如何一次只呈现numberOfItems Items 2.如何在单击项目时使项目消失并显示下一项目,而不会触发重新呈现其他项目

我正在使用Array.map来渲染项目,但是当我只想渲染它们的某个子集时,这会呈现所有项目,然后还试图弄清楚如何处理解雇的逻辑。

1 个答案:

答案 0 :(得分:0)

您可以使用filter获取尚未被解雇的项目,然后将splice应用于剩余项目以限制呈现的数量:



const items = [{ id: 0, message: 'Test 1'},{ id: 1, message: 'Test 2'},{ id: 2, message: 'Test 3'},{ id: 3, message: 'Test 4'},{ id: 4, message: 'Test 5'},{ id: 5, message: 'Test 6'}]

class App extends React.Component {

  state = {
    notifications: items,
    displayAmt: 2
  };

  renderNotifications = () => {
    const { notifications, displayAmt } = this.state;
    
    // First, filter out all notifications that have been dismissed
    // Then, splice the remaining items to only get n amount at a time
    // Last, map over the remaining items and render them
    return notifications.filter( notification => !notification.dismissed )
      .splice(0, displayAmt)
      .map( notification => (
        <li onClick={() => this.dismissNotification(notification.id)} key={notification.id}>  
          {notification.message}
        </li>
      ));
    
  };
  
  dismissNotification = id => {
  
    // Use the id passed in to update the item in state from dismissed: false -> true
    const notifications = this.state.notifications.map( notification => {
      if(notification.id === id) {
        notification.dismissed = true;
      }
      return notification;
    });
    this.setState({ notifications });
  };

  render() {
    const notifications = this.renderNotifications();
    return (
      <ul>
        {notifications}
      </ul>
    )
  }
}


ReactDOM.render(<App/>, document.getElementById('root'));
&#13;
li {
  cursor: pointer;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
&#13;
&#13;
&#13;