React shouldComponentUpdate() メソッド

React 组件生命周期React コンポーネントのライフサイクル

shouldComponentUpdate() メソッドの形式は次のとおりです:

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate() メソッドはブール値を返し、React がレンダリングを続行するかどうかを指定します。デフォルト値はtrue、つまりstate毎回変化が発生するとコンポーネントは再レンダリングされます。

shouldComponentUpdate() の戻り値は、React コンポーネントの出力が現在の state または props の変更によって影響を受けるかどうかを判断するために使用されます。props または state が変更されると、shouldComponentUpdate() はレンダリングの実行前に呼び出されます。

次の実例は、shouldComponentUpdate() メソッドが false を返したときに実行される操作を示しています(ボタンをクリックしても変更できません):

実例

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "サンプル"}; } shouldComponentUpdate() { return false; } changeSite = () => { this.setState({favoritesite: "google"}); } render() { return ( <div> <h1>私の好きなウェブサイトは{this.state.favoritesite}</h1> <button type="button" onClick={this.changeSite}>変更</button> </div> ); } }

試してみる »

次の実例は、shouldComponentUpdate() メソッドが true を返したときに実行される操作を示しています(ボタンをクリックすると変更できます):

実例

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "サンプル"}; } shouldComponentUpdate() { return true; } changeSite = () => { this.setState({favoritesite: "google"}); } render() { return ( <div> <h1>私の好きなウェブサイトは{this.state.favoritesite}</h1> <button type="button" onClick={this.changeSite}>変更</button> </div> ); } }

試してみる »

React 组件生命周期React コンポーネントのライフサイクル

その他の拡張