React.js:shouldComponentUpdate在无状态子组件数组中
React.js: shouldComponentUpdate in array of stateless child Components
我有一个父React类(<EventList />
),它包含一个存储其子组件(<Event />
)数据的对象。为了简洁起见,我省略了许多函数。
EventList
的现状背景
/**
* The events state looks like this before the EventList component is rendered:
*
* var events = {
* 1: {
* id: 1,
* title: "Some title"
* },
* 2: {
* id: 2,
* title: "Some other title"
* },
*
* ...
* };
*/
事件.jsx
var Event = React.createClass({
/**
* Pass up the ID of the Event and the new value of the Event's Title
*/
_handleChange: function (e) {
this.props.handleChange(this.props.id, e.target.value);
},
render: function () {
return (
<div className="event">
<input type="text" value={this.props.title} onChange={this._handleChange} />
</div>
);
}
});
事件列表.jsx
var EventList = React.createClass({
propTypes: {
events: React.PropTypes.object
},
/**
* Update the State of an event who's title has changed
*/
_handleChange: function (id, title) {
var newState = React.addons.update(this.state.events[id].title, {
$set: title
});
this.setState(newState);
},
render: function () {
var renderedEvents = Object.keys(this.state.events).map(function (id) {
var event = this.state.events[id];
return <Event key={event.id} title={event.title} handleChange={this._handleChange}/>;
}, this);
return (
<div className="events">
{renderedEvents}
</div>
);
}
});
现在这很好,而且有效。标题的状态会得到更新,所有内容都会成功渲染和重新渲染;但这也是问题所在:
一切都重新渲染
列表中有几个事件也不错,但一旦有大量事件,当EventList
渲染函数通过并填充<Event />
组件的新阵列时,重新渲染会带来巨大的性能损失。
我希望能够做的一件事(尽管假设这需要对应用程序进行完整的重组)是能够在<Event />
组件中使用shouldComponentUpdate
。
然而,以我目前的关系,我不能这样做。如果您查看shouldComponentUpdate
:的默认参数
shouldComponentUpdate: function(nextProps, nextState) {...},
您会注意到,在<Event />
级别上,this.props
将始终等于nextProps
,因此尝试执行以下操作:
shouldComponentUpdate: function(nextProps, nextState) {
return this.props !== nextProps;
},
将始终返回CCD_ 12,因为在事物流的这一点上,它们指向完全相同的数据集。CCD_ 13当然不存在于CCD_。
因此,我的问题是,我需要做些什么来摆脱<EventList />
级别上极其昂贵的重新渲染?
问题出在您的更新调用中。目前,您基本上执行var newState = title
。您需要实际更新顶级状态密钥。
_handleChange: function (id, title) {
var update = {};
update[id] = {title: {$set: title}};
var newEvents = React.addons.update(this.state.events, update);
this.setState({events: newEvents});
},
或者使用ES6,您可以避免本地变量:
_handleChange: function (id, title) {
var newEvents = React.addons.update(this.state.events, {
[id]: {
title: {$set: title}
}
});
this.setState({events: newEvents});
},
相关文章:
- 不能从angular2中的子组件指定父组件中的数组
- 从组件状态的数组中删除元素
- 将ember对象的数组从ember组件传递到模板
- 如何在cycle js中从JSON数组创建组件
- 使用数据数组创建多个类似组件
- 如何创建独立于数组更新的组件列表
- 访问要在 React Native Text 组件中显示的对象数组
- React:用CSS类标记数组中的活动组件
- 如何在 Vue.js 中保持可排序的数组和组件的顺序
- 使用 React 将数组导出为组件属性
- 如何使用组件从 vuejs 中获取纯数组
- 对React Native中从父组件传下来的props数组进行更改
- ReactJS中使用非子组件的子数组唯一键
- 聚合物网络组件数据绑定一个js对象/数组
- 如何访问foreach中Knockout组件中的数组成员
- React不能从组件中渲染数组
- Angular2 -在路由和渲染组件之前,通过service获取数组
- #每个循环不检测组件中定义的数组
- 从react组件'数组类型状态属性弹出的正确方式
- Mithril.js:为什么“组件模板必须返回一个虚拟元素,而不是数组、字符串等”?的意思