我正在尝试在 ES6 中使用有状态的 React 组件,但是当我定义构造函数时,构造函数只会在多次渲染组件(从其父级)时调用一次。示例如下所示。
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
不需要状态,但我尝试使其尽可能简单以显示我的问题。
我错过了什么?