私はリアクションアプリケーションに取り組んでいて、shouldComponentUpdate()
を使用しないとコンポーネントが絶えず更新される状況に遭遇しました。私はこれがこの種の変更を処理する最善の方法かどうか、または私のコードをリファクタリングしようとするべきかどうかを判断しようとしているので、この方法で更新を止める必要はありません。shouldComponetUpdateを使用して状態セットループを解除しますか?
私の実際のコードは他にもたくさんありますので、いくつかのダミーの例をまとめます。
親コンポーネント:
class App extends React.Component {
constructor() {
super();
this.stateChange = this.stateChange.bind(this);
this.state = {
foo: 'bar'
}
}
stateChange(change) {
this.setState({foo: change});
}
render() {
return (
<div>
<p>Hello World</p>
<ChildComponent stateChange={this.stateChange} />
</div>
)
}
}
子コンポーネント:
class ChildComponent extends React.Component {
constructor() {
super();
this.renderDecision = this.renderDecision.bind(this);
this.updateStage = this.updateStage.bind(this);
this.state = {
stage: [1],
hello: 'world'
}
}
updateStage(e) {
let theStage = [...this.state.stage];
theStage.push(1);
this.setState({stage: theStage});
}
renderDecision() {
if (this.state.stage.length < 3) {
return (
<p>There are {this.state.stage.length} items. <button onClick={(e) => this.updateStage(e)}>Click here to update.</button></p>
)
} else if (this.state.stage.length === 3) {
this.props.stateChange(this.state.hello); /// updates the parent which updates the child which updates the parent... ad infinitum
return (
<p>Hello {this.state.hello}, there are {theStage} items.</p>
)
}
}
render() {
return (
<div>
(this.renderDecision())
</div>
)
}
}
stage
配列は、長さが3に到達し、そこにとどまる一度あなたが見ることができるように、アプリ&子コンポーネントは、Aにロックを取得設定状態のループ。
これはChildComponent
にこのような何かを追加することによって固定することができます -
componentShouldUpdate() {
if (this.state.stage.length === 3) {
return false;
} else return true;
}
しかし、私が知りたいことは、私は他のいくつかの解決策を考え出す必要がある場合は、これがベストプラクティスである、またはかどうかではありません。アプリケーションの残りの部分が何が起こっているのかを知る必要なく、約6つの異なるパラメータを順番に循環するので、私の子コンポーネントは状態を持っているので、stage
をすべて渡すことでアプリケーション全体を再レンダリングするのは意味がありません親にバックアップする。
この質問は理にかなっています。読んでくれてありがとう。
ああ、いいえ!うわー。これは、たくさんのお手伝いをします。 (私の実際のコードでは、私の状態変更の決定の大部分は、ユーザ入力で実行される関数にラップされていますが、私のループを引き起こすものはありません。 – JSilv