【问题标题】:React: Get initialstate after state has changed反应:状态改变后获取初始状态
【发布时间】:2014-08-30 03:19:09
【问题描述】:

在状态改变之后是否可以检索初始状态?前:

React.createClass({
  getInitialState: function() {
    return { foo: 'bar' }
  },
  componentWillMount: function() {
    this.setState({ foo: 'foo' })
  },
  componentDidMount: function() {
    // get the initial state "bar" ?
  }
})

我在文档中找不到任何内容。我当然可以将值保存在外部变量中,但如果可以将初始状态视为可以重用的“配置”对象,我只是好奇。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    不,不存储初始状态 -- 但如果您想重新执行该函数,可以调用 this.getInitialState()

    【讨论】:

      【解决方案2】:

      只需将初始状态保存在一个变量中:

      React.createClass({
          initialState: { foo: 'bar' },
      
          getInitialState   : function () {
              return this.initialState;
          },
          componentWillMount: function () {
              this.setState({ foo: 'foo' })
          },
          componentDidMount : function () {
              console.log(this.initialState.foo); // Logs 'bar'
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2019-07-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-08
        • 2021-06-18
        • 1970-01-01
        相关资源
        最近更新 更多