我试图在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),但是日志将输出:
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不需要状态,但是我尝试使其尽可能简单以显示我的问题。
SubComponent
我想念什么?
我建议阅读getInitialState是Anti- Pattern中的Props。
基本上,尽可能少的组件应该具有状态。正如其他答案已经说过的,在您的情况下,您可以仅使用this.props.count引用当前值。似乎没有任何理由SubComponent应该具有自己的状态。
this.props.count
但是,如果您确实想根据收到的道具计算组件的状态,则有责任使用生命周期方法使它们保持同步componentWillReceiveProps:
componentWillReceiveProps
componentWillReceiveProps(nextProps) { this.setState({count: nextProps.count}); }