reactjs - 用新值更新数组对象的状态真的很慢
问题描述
我的数据集比下面的示例大得多。我正在尝试向配置文件添加注释,但是,在键入和出现在 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>
);
}
}
解决方案
您可以传递配置文件的索引以在更改处理程序中更新,然后直接更新该配置文件。
// 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
与每个文本区域一起使用,以便反应不会在每次渲染时重新渲染每个文本区域。
推荐阅读
- reactjs - React-native 和 Redux 设置状态和渲染
- python - 3列的嵌套字典,其中一列通过顶级字典键重复类别
- javascript - 连接的音频文件未按预期播放
- c# - Xamarin.Forms 图像源绑定到字符串 (MVVM)
- mongodb - 在 M1 mac 上安装 mongodb
- javascript - Electron - 未使用 GPU 且应用程序中的帧速率较低
- nginx - 在 NGINX 旁边安装 XMPP 服务器(如 Prosody)
- mysql - 获取cursor.close()UnboundLocalError:调用/api/view/addmin时在赋值错误之前引用局部变量'cursor'
- php - PHP Mailer:从 html 文件发送时 XLSX 文件损坏
- java - 如何在方法中将类对象作为参数传递?