首页 > 解决方案 > 用新值更新数组对象的状态真的很慢

问题描述

我的数据集比下面的示例大得多。我正在尝试向配置文件添加注释,但是,在键入和出现在 textarea 中的文本之间存在相对较大的滞后。我认为这种情况会发生,因为它必须经过大量数据。有没有更有效的方法来做到这一点。

数据

const profiles = [{
  firstName: 'Brady',
  lastName: 'Smith'
}, {
  firstName: 'Jason',
  lastName: 'Brady'
}, {
  firstName: 'Michael',
  lastName: 'Bolten'
}];

零件

class Notes extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      profiles: []
    };
    this.handleAddingUserNotes = this.handleAddingUserNotes.bind(this);
  }

  handleAddingUserNotes(e, userId) {
    const { profiles } = this.state;

    const addNotesToProfiles = profiles.map(profile => {
      if (profile.userId === userId) {
        profile.notes = e.target.value;
      }
      return profile;
    });

    this.setState({ profiles: addNotesToProfiles });
  }

  render() {
    const { profiles } = this.state;

    return (
      <div>
        {profiles.map(profile => {
          const { userId, notes } = profile;

          return (
            <textarea
              className="form-control"
              value={notes}
              onChange={e => this.handleAddingUserNotes(e, userId)}
            />
          );
        })}
      </div>
    );
  }
}

标签: reactjs

解决方案


您可以传递配置文件的索引以在更改处理程序中更新,然后直接更新该配置文件。

// in your render method
{profiles.map((profile, index) => {
          const { userId, notes } = profile;

          return (
            <textarea
              className="form-control"
              value={notes}
              onChange={e => this.handleAddingUserNotes(e, index, userId)}
            />
          );
        })}

// in your handle change
handleAddingUserNotes(e, index, userId) {
    const { profiles } = this.state;

    const newProfiles = [...profiles.slice(0, index), {...profiles[index], notes: e.target.value}, ...profiles.slice(index+1)]

    this.setState({ profiles: newProfiles });
  }

或者,如果您对每个用户都有唯一的 userId,则可以将整个数组转换为每个用户由 索引的对象,userId然后直接在 userProfiles 对象中更新该用户。O(1) 操作。

编辑:是的,正如另一个答案所提到的,请key与每个文本区域一起使用,以便反应不会在每次渲染时重新渲染每个文本区域。


推荐阅读