我試圖使用帶有一個ES6狀態作出反應成分,但是當我定義了一個構造函數,同時組件被渲染多次(從它的父構造函數只會被調用一次保持狀態的組件作出反應)。示例如下所示。我如何使用ES6
class SubComponent extends React.Component {
constructor(props) {
super(props);
console.log("Creating sub component");
this.state = { count: props.count };
}
render() {
console.log("Rendering sub component", this.state.count);
return (<div>count: {this.state.count}</div>);
}
}
class App extends React.Component {
constructor(props) {
super(props);
console.log("Creating app");
this.state = { count: 0 };
this.tick = this.tick.bind(this);
setInterval(this.tick, 1000);
}
tick() {
this.setState({ count: this.state.count + 1 });
}
render() {
console.log("Rendering app", this.state.count);
return (<SubComponent count={this.state.count} />);
}
}
這將不會更新渲染輸出(它總是會count: 0
),但日誌將輸出:
Creating app
Rendering app 0
Creating sub component
Rendering sub component 0
Rendering app 1
Rendering sub component 0
Rendering app 2
Rendering sub component 0
Rendering app 3
Rendering sub component 0
...
這裏有一個的jsfiddle:http://jsfiddle.net/jor0xu1a/1/
我知道的例子SubComponent
不需要一個狀態,但我試圖儘可能簡單地顯示我的問題。
我錯過了什麼?
,我會在這裏張貼了我的答案,如果我只看到你的帖子之前:)是啊,這是我相信的是,父母總是錯誤重新創建上重新渲染它的孩子。 'componentWillReceiveProps'解決了我的困境,謝謝你的幫助! –