我试图了解如果使用状态如何发送新变量。
这是 React 教程中的示例:
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);
它有效。但如果我想发送secondsElapsed
我该怎么办?
<Timer sec={this.props.sec}>
和:
getInitialState: function() {
return {secondsElapsed: this.props.sec};
}
这不起作用。
JSFIDDLE - 我应该从 10000 秒开始计时器。
最佳答案
code下面按预期工作。除了确保 initialTime
属性始终具有默认值之外,您还可以在 getInitialState
中初始化 secondsElapsed
状态。虽然这样做可以被认为是 anti-pattern ,在这种情况下,它不是因为它只是进行内部状态的初始化。
此外,您还需要实现 componentWillReceiveProps
。当组件的 props 更新时,这个函数就会被调用(第一次之后)。在本例中,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>
);
}
});
如果您可能要将字符串传递到 initialTime
(如上所示),请确保对值使用 parseInt
:
return { secondsElapsed: parseInt(this.props.initialTime || '0') };
了解有关组件生命周期的更多信息 here .
关于javascript - 在状态中发送 props - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28466762/