React: update one item in a list without recreating all items

前端 未结 6 605
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 05:27

Let\'s say I have a list of 1000 items. And I rendering it with React, like this:

class Parent extends React.Component {
  render() {
    // this.state.list is a         


        
6条回答
  •  难免孤独
    2021-01-30 06:03

    You can do it by using any state management library, so that your Parent doesn't keep track of this.state.list => your List only re-renders when new Item is added. And the individual Item will re-render when they are updated.

    Lets say you use redux.

    Your code will become something like this:

    // Parent.js
    class Parent extends React.Component {
      render() {        
        return ;
      }
    }
    
    // List.js
    class List extends React.Component {
      render() {        
        var list = this.props.list.map(item => {
          return ;
        });
        return 
    {list}
    ; } } const mapStateToProps = (state) => ({ list: getList(state) }); export default connect(mapStateToProps)(List); // Item.js class Item extends React.Component { shouldComponentUpdate() { } render() { } } const mapStateToProps = (state, ownProps) => ({ item: getItemByKey(ownProps.uniqueKey) }); export default connect(mapStateToProps)(Item);

    Of course, you have to implement the reducer and the two selectors getList and getItemByKey.

    With this, you List re-render will be trigger if new elements added, or if you change item.key (which you shouldn't)

提交回复
热议问题