Javascript 在状态下发送道具-反应
我试图理解如果我使用state,如何发送新变量 这是React教程中的示例:Javascript 在状态下发送道具-反应,javascript,reactjs,Javascript,Reactjs,我试图理解如果我使用state,如何发送新变量 这是React教程中的示例: var Timer = React.createClass({ getInitialState: function() { return {secondsElapsed: 0}; }, tick: function() { this.setState({secondsElapsed: this.state.secondsElapsed + 1}); }, componentDidMo
var Timer = React.createClass({
getInitialState: function() {
return {secondsElapsed: 0};
},
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render: function() {
return (
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>
);
}
});
React.render(<Timer />, mountNode);
它不起作用
-我应该从10000秒开始计时。签出组件willmount() 如果您在componentWillMount中调用setState,则可以保证它在进入渲染之前会被更新。下面的操作与预期的一样。除了确保
initialTime
属性始终有一个默认值之外,您还可以在getInitialState
中初始化secondsElapsed
状态。虽然这样做可能会被认为是一个错误,但在这种情况下,这并不是因为它只是在初始化内部状态
此外,您还需要实现组件willreceiveprops
。当组件的道具更新后(第一次之后)调用此函数。在这种情况下,initialTime
属性值最初为10
,然后更改为10000
。因此,nextProps
参数将包含一个属性initialTime
设置为10000
的对象
var Timer = React.createClass({
getInitialState: function() {
return { secondsElapsed: this.props.initialTime || 0 };
},
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentWillReceiveProps: function(nextProps) {
this.setState({ secondsElapsed: nextProps.initialTime || 0 });
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render: function() {
return (
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>
);
}
});
阅读有关组件生命周期的更多信息。我尝试了
componentWillUpdate:function(){console.log(1)this.setState({secondsElapsed:this.props.duration});},
console打印“1”1200次。componentWillMount
只更改一次。如果我更改道具,则不会更改。不幸的是,在我的例子中,initialTime
具有初始状态,并且从JSON加载时。而且initialTime
总是0
但是initialTime
更新。'componentWillMount:function(){this.setState({secondsElapsed:this.props.initialTime});}'也没有帮助。请看我的例子——在例子中我设置了新的时间——10000sec.ah——现在我明白你在找什么了。查看我的更新,其中包含组件willreceiveprops
。
var Timer = React.createClass({
getInitialState: function() {
return { secondsElapsed: this.props.initialTime || 0 };
},
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentWillReceiveProps: function(nextProps) {
this.setState({ secondsElapsed: nextProps.initialTime || 0 });
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render: function() {
return (
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>
);
}
});
return { secondsElapsed: parseInt(this.props.initialTime || '0') };