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.props
constructor
render
shouldComponentUpdate
これはソフィー・アルパートの著書で明確に述べられている。答え同様の質問に対して。
ドキュメント—状態とライフサイクル、クラスへのローカル状態の追加、ポイント 2—推奨:
クラス コンポーネントは常に で基本コンストラクターを呼び出す必要があります
props
。
ただし、理由は示されていません。サブクラス化のためか、将来の互換性のためかのいずれかであると推測できます。
(リンクを提供してくれた@MattBrowneに感謝します)