es6 クラスを使用する場合、React の「super()」と「super(props)」の違いは何ですか? 質問する

es6 クラスを使用する場合、React の「super()」と「super(props)」の違いは何ですか? 質問する

propsにパスすることが重要なのはいつですかsuper()、またその理由は何ですか?

class MyComponent extends React.Component {
  constructor(props) {
    super(); // or super(props) ?
  }
}

ベストアンサー1

propsに渡す必要がある理由は 1 つだけですsuper()

コンストラクターでアクセスしたい場合this.props

通過:

class MyComponent extends React.Component {    
    constructor(props) {
        super(props)

        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

不合格:

class MyComponent extends React.Component {    
    constructor(props) {
        super()

        console.log(this.props)
        // -> undefined

        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
    }

    render() {
        // No difference outside constructor
        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

propsに渡すか渡さないかは、後続の の外側の使用には影響superないことに注意してください。つまり、、、またはイベント ハンドラーは常に にアクセスできます。this.propsconstructorrendershouldComponentUpdate

これはソフィー・アルパートの著書で明確に述べられている。答え同様の質問に対して。


ドキュメント—状態とライフサイクル、クラスへのローカル状態の追加、ポイント 2—推奨:

クラス コンポーネントは常に で基本コンストラクターを呼び出す必要がありますprops

ただし、理由は示されていません。サブクラス化のためか、将来の互換性のためかのいずれかであると推測できます。

(リンクを提供してくれた@MattBrowneに感謝します)

おすすめ記事