[英]How can i keep state in a React component using ES6
我试图在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
不需要状态,但是我尝试使其尽可能简单以显示我的问题。
我想念什么?
在SubComponent中, props
不是状态-将其更改为this.props.count
,它将起作用
我建议阅读getInitialState中的Props是Anti-Pattern 。
基本上,应该有尽可能少的组件具有状态。 正如其他答案已经说过的那样,您可以使用this.props.count
引用当前值。 似乎没有任何原因使SubComponent
具有自己的状态。
但是,如果您真的想根据收到的道具计算组件的状态,则有责任使用生命周期方法componentWillReceiveProps
使它们保持同步:
componentWillReceiveProps(nextProps) {
this.setState({count: nextProps.count});
}
您的子组件应为:
class SubComponent extends React.Component {
constructor(props) {
super(props);
console.log("Creating sub component");
}
render() {
return (<div>count: {this.props.count}</div>);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.