簡體   English   中英

如果子組件的props不變,React是否仍然重新渲染它?

[英]If the props for a child component are unchanged, does React still re-render it?

假設我在React中有以下父組件和子組件配對:

var ChildComponent = React.createClass({
    getDefaultProps: function(){
        return {
            a: 'a',
            b: 'b',
            c: 'c'
        }
    },

    render: function() {
        return (
            /* jshint ignore:start */
            <div className={'child' + (this.props.b ? ' modifierClass' : '')} something={this.props.a}>
                {this.props.c}
            </div>
            /* jshint ignore:end */
        );
    }
});


var ParentComponent = React.createClass({
    componentDidMount: function(){
        //After 10 seconds, change a property that DOES NOT affect the child component, and force an update
        setTimeout(function(){
            this.setState({foo: 'quux'});
            this.forceUpdate();
        }.bind(this), 10000);
    }

    getInitialState: function(){
        return {
            foo: 'bar',
            a: 1,
            b: 2,
            c: 3
        }
    },

    render: function() {
        return (
            /* jshint ignore:start */
            <div className="parent">
                <ChildComponent a={this.props.a} b={this.props.b} c={this.props.c}/>
            </div>
            /* jshint ignore:end */
        );
    }
});


React.render(
    /* jshint ignore:start */
    <ParentComponent />, 
    /* jshint ignore:end */
    document.getElementsByTagName('body')[0]
);

當我執行forceUpdate ,由於傳遞給ChildComponent的所有道具都沒有更改,React會嘗試重新渲染嗎? 如果我有1000個這樣的孩子怎么辦?

我擔心的是一種情況,我有一個非常深的ChildComponent包含一個完整的后代組件樹,但我只想在ParentComponent上進行一些相對美觀的更改。 有沒有辦法讓React只更新父級,而不嘗試重新渲染子級?

當React重新呈現ParentComponent ,它將自動重新呈現ChildComponent 解決方法的唯一方法是在shouldComponentUpdate中實現ChildComponent 您應該比較this.props.athis.props.bthis.props.c以及ChildComponents自己的狀態來決定是否重新渲染。 如果你使用不可變數據,你可以使用嚴格相等===來比較上一個和下一個狀態和道具。

您的代碼有一些注意事項

  1. setState時不需要forceUpdate React會自動為您完成。
  2. 你可能意味着:

    <ChildComponent a={this.props.a} b={this.props.b} c={this.props.c}/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM