2017-11-29 3 views
0

私は親コンポーネントによってその小道具が設定されているコンポーネントを持っています。親コンポーネントは定期的に変更されますが、子コンポーネントの小道具は変更されません。小道具と状態が変わっていなくても、Reactコンポーネントがレンダリングされる原因は何ですか?

しかし、子供はレンダリングを続けていますが、理由を理解できません。

shouldComponentUpdate(nextProps, nextState) { 
    console.info(JSON.stringify(nextProps)+JSON.stringify(nextState)); 

    console.info('NEXT PROPS ===================='); 
    for (var n in nextProps) { 
     if (!nextProps.hasOwnProperty(n)) continue; 
     console.info(n + ' = ' + (nextProps[n] === this.props[n])); 
    } 

    console.info('NEXT STATE ===================='); 
    for (var n in nextState) { 
     if (!nextState.hasOwnProperty(n)) continue; 
     console.info(n + ' = ' + (nextState[n] === this.state[n])); 
    } 

    return true; 
} 

これは、コンソールに次のように出力されます::小道具や状態は、私はこの機能を追加しました変更されていないことを確認するには

{"autocomplete":null,"value":"","theme":1,"style":{"width":1426,"height":783},"label":"","description":null,"visible":false,"buttons":null,"inputType":null}{"visible":false,"answer":""} 
NEXT PROPS ==================== 
autocomplete = true 
value = true 
theme = true 
style = true 
onClose = true 
label = true 
description = true 
visible = true 
buttons = true 
inputType = true 
NEXT STATE ==================== 
visible = true 
answer = true 

{"autocomplete":null,"value":"","theme":1,"style":{"width":1426,"height":783},"label":"","description":null,"visible":false,"buttons":null,"inputType":null}{"visible":false,"answer":""} 
NEXT PROPS ==================== 
autocomplete = true 
value = true 
theme = true 
style = true 
onClose = true 
label = true 
description = true 
visible = true 
buttons = true 
inputType = true 
NEXT STATE ==================== 
visible = true 
answer = true 

だから、次の状態への1つの呼び出しからと小道具は厳密に等しいが、このコンポーネントのrender()関数が呼び出され続ける。このshouldComponentUpdate()はテストのためのものであり、私がそれを削除した場合、render()も同じ条件のもとで呼び出され続けることに注意してください。

これを引き起こす原因は何ですか?

+0

子コンポーネントは、子コンポーネントの小道具が同じままであっても、親コンポーネントが更新される場合に再レンダリングされます。子の再レンダリングを避けたい場合は、単にshouldComponentUpdateメソッドから 'false'を返します。 –

答えて

4

コンポーネントがあります。コンポーネントは親コンポーネントによって設定されています。 親コンポーネントは定期的に変更されますが、子の小道具は ではありません。しかし何らかの理由で子どもがレンダリングを続けるが、私はなぜ を見つけられないのだろうか。

子は、親のレンダリングメソッドの内部にあるので、再レンダリングを維持します。

良く、子供がを呼び出されますなぜを参照してくださいJSXが戻って通常のJSに変換し得ることを覚えているので、何か好きに:

render() { 
    return (
    ... 
    <ChildComponent someProp={"hello"} /> 
    ... 
); 
} 

は次のようになります。

render() { 
    return React.createElement(
    ..., 
    React.createElement(ChildComponent, { someProp: "hello" }), 
    ... 
); 
} 

そうでない場合は子供が再レンダリングされるようにしたい場合は、その小道具が変更されていないかどうかを確認してをshouldComponentUpdateの中に返すか、またはReact.PureComponentから拡張してくださいatically - see the difference

Re-rendering!== re-drawingを実行すると、Reactのdiffingアルゴリズムが実行されます。また、diffingアルゴリズムでは、現在のバージョンの仮想DOMが以前のバージョン仮想DOMは、UIの特定の「変更された」部分を画面上に再描画します。

関連する問題