我有一个 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
render 函数遍历并填充一个新数组 <Event />
成分。
我希望能够做的一件事(尽管假设它需要对应用程序进行完全重组)是能够利用 shouldComponentUpdate
在 <Event />
内组件。
但是,以我目前的关系,我不能这样做。如果您查看 shouldComponentUpdate
的默认参数:
shouldComponentUpdate: function(nextProps, nextState) {...},
您会注意到在 <Event />
水平,this.props
永远等于 nextProps
,所以尝试做类似的事情:
shouldComponentUpdate: function(nextProps, nextState) {
return this.props !== nextProps;
},
将始终返回 false
因为在事物流的这一点上,它们指向完全相同的数据集。 nextState
当然不存在于<Event />
水平。
所以我的问题是,我需要做什么才能摆脱在 <EventList />
处进行的极其昂贵的重新渲染?水平?
最佳答案
问题出在您的更新调用中。目前,您实际上是在执行 var newState = title
。您实际上需要更新顶级状态 key 。
_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});
},
关于javascript - react .js : shouldComponentUpdate in array of stateless child Components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28844913/