javascript - 在状态中发送 props - React

标签 javascript reactjs

我试图了解如果使用状态如何发送新变量。

这是 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/

相关文章:

reactjs - 在 React 中隐藏和显示外部组件

javascript - 如何使用 es6 从文件导入 jQuery

javascript - 当通过表单按 Tab 键 (32) 时,icheck.js 单选按钮会自动被选中

javascript - 如何在 Javascript 中将文本添加到弹出窗口?

javascript - React - JSX 语法问题,以及如何迭代 map 并在换行符上显示项目

reactjs - 如何正确处理react-router中的子路由(路由有效,但URL随着每次点击而增长)

javascript - 当第二次点击按钮时做某事

javascript - 如何通过javascript将父子数组转换为json树结构

html - 如何使用javascript在jsx中重复插入特殊字符?

reactjs - 如何修复 "SyntaxError: Cannot use import statement outside a module"