0

我正在使用 React Flux 架构开发项目。我的控制器视图看起来像

var MyComponent = React.createClass({
    getInitialState: function() {
        return MyStore.getData();
    },
    render: function() {
        return <ul className="navigation">
                   <UserControl/>
                   <NavigationBar change={this._onChange} messageCounter={this.state.data.score}/>
               </ul>
    },
    _onChange: function() {
        this.setState(Store.getData());
    }
});

我在渲染函数中有一些嵌套视图,并且在某些视图中所做的每一个更改都会导致控制器视图渲染函数运行。这会导致所有嵌套组件的渲染功能也运行,但唯一的变化将在 UserControl 组件上。我不需要运行所有嵌套组件的渲染函数。

我该如何解决?
它是通量架构的行为吗?
如何减少渲染函数调用的次数?

4

1 回答 1

1

简短的回答是覆盖 shouldComponentUpdate 方法: http ://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate

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

该方法接收状态和道具更新,因此您可以确定该组件的任何数据是否已更改。如果不是,则返回 false,并且该组件将不会呈现。

更重要的是,你真的需要担心那些额外的渲染吗?如果您没有看到真正的性能问题,我会保留它。这是 React 的 DOM 操作方法的主要优点之一。如果组件呈现,并且没有任何更改,则 DOM 将保持不变。

于 2015-01-27T17:39:04.330 回答