1

親コンポーネントではなく、子コンポーネント内で componentDidUpdate() ライフサイクルを定義しました。

親コンポーネント:

class App extends Component {

    state = {
      count:0,
    }

    change = () =>{
      this.setState({
        count:this.state.count+1,
      })
    }

    render() {

      return (
        <div>
          <p>Count = {this.state.count}</p>
          <button onClick={this.change}>Add Count</button>
          <NewComp />
        </div>
      );
    }
}

子コンポーネント:

export default class NewComp extends Component {

  componentDidUpdate(){
    console.log('Child component did update');
  }

  render() {
    return (
      <div>
        <h1>Child Component</h1>
      </div>
    )
  }
}

「Add Count」ボタンで親の状態を変更するたびに、子コンポーネントに変更がなくても、子コンポーネントの componentDidMount() が実行されます

4

4 に答える 4

0

以下のクエリを見ることができます。あなたに似ているのはどれですか

React:親コンポーネントは、状態の変更時に変更されていないものも含め、すべての子を再レンダリングします

お役に立てば幸いです。

于 2019-01-29T07:23:33.643 に答える