在状态下发送道具 - React

Send props in state - React

我正在尝试了解如何在使用状态时发送新变量。

这是 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 秒开始计时

查看 componentWillMount (http://facebook.github.io/react/docs/component-specs.html)

如果您在 componentWillMount 中调用 setState,您可以保证它会在渲染之前更新。

code below works as expected. Other than making sure there's a default value always for the initialTime property, you can initialize the secondsElapsed state within getInitialState. While doing this could be considered an 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