首页 文章

React.js:无状态子组件数组中的shouldComponentUpdate

提问于
浏览
1

我有一个父React类( <EventList /> ),它包含一个存储's it'子组件( <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"
 *      },
 *
 *      ...
 * };
 */

Event.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>
        );
    }
});

EventList.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>
        );
    }
});

现在这很好,它的工作原理 . Headers 的状态会更新,所有内容都会成功呈现和重新呈现;但这也是问题所在:

一切都重新呈现!

它的数量很多,重新渲染会带来巨大的性能损失,因为 EventList 渲染功能会通过并填充一个新的 <Event /> 组件数组 .

我需要完全重组应用程序的一件事是能够在 <Event /> 组件中使用 shouldComponentUpdate .

但是,根据我目前的关系,我不能这样做 . 如果你看一下 shouldComponentUpdate 的默认参数:

shouldComponentUpdate: function(nextProps, nextState) {...},

您会注意到 <Event /> 级别, this.props 将始终等于 nextProps ,因此尝试执行以下操作:

shouldComponentUpdate: function(nextProps, nextState) {
    return this.props !== nextProps; 
},

将始终返回 false 因为在这一点上他们指向完全相同的数据集 . nextState 当然在 <Event /> 级别不存在 .

所以我的问题是,我需要做些什么来摆脱 <EventList /> 级别非常昂贵的重新渲染?

1 回答

  • 4

    问题出在您的更新通话中 . 目前,你基本上做 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});
    },
    

相关问题