在重新渲染期间更新状态的问题

时间:2015-06-10 14:50:42

标签: javascript reactjs

我有2个组件,一个StaticComponent和一个InteractiveComponent。 StaticComponent显示用户的信息。它有一个编辑链接 信息。该链接有一个onClick,用于触发handleEditClick函数。这将使用具有表单的InteractiveComponent替换StaticComponent。

var StaticComponent = React.createClass({
  handleEditClick: function (event) {
    event.preventDefault();
    React.render(<InteractiveComponent user_info={this.props.user_info}  
                                       form_status={'form-to-be-sent'} />, 
                  document);
  },
})

InteractiveComponent从props设置user_info的状态。它也是 将状态formSubmissionStatus值指定为“待发送形式”&#39;为了 初始状态,再次来自道具。该组件还有一个handleSubmit函数,显然还有render函数。

var InteractiveComponent = React.createClass({
  getInitialState: function() {
    return {
      user_info: JSON.parse(this.props.user_info),
      formSubmissionStatus: this.props.form_status
    };
  },

  handleSubmit: function(event, data) {
    // ...
  },

  render: function() {
    // ...
  }
});

render函数有一个在提交时调用handleSubmit的表单。它还会分配一个userInfo,它将新道具设置为道具中的现有user_info数据,或者来自州的更新信息,具体取决于表单的提交状态。

如果状态设置为“要发送的形式”,则渲染功能也会呈现表单,否则将呈现静态组件。这是因为它假设表格已提交。

render: function () {
  var profileForm = (
      <form ref="form" onSubmit={ this.handleSubmit }>
        <label>Your Name</label>
        <textarea id="user_name" defaultValue={this.state.user_info.name} ref='name' />
        <button className='greenbutton' type="submit">Update</button>
      </form>
    );

  var userInfo = this.state.formSubmissionStatus == 'form-to-be-sent' ? this.props.user_info : JSON.stringify(this.state.user_info);

  return (
    this.state.formSubmissionStatus == 'form-to-be-sent' ? profileForm : <StaticComponent user_info={userInfo} />
  );
}

handleSubmit在新的关联数组中更新用户信息,并向服务器提交ajax POST。在ajax调用之前,它会将用户信息的状态更新为最新数据,并更新formSubmissionStatus值。

handleSubmit: function(event, data) {
    event.preventDefault();

    var formData = $(this.refs.form.getDOMNode()).serialize(),
        latestUserInfo = JSON.parse(this.props.user_info),
        name = this.refs.name.getDOMNode().value.trim(),
        that = this;

    latestUserInfo['name'] = name;

    $.ajax({
      data: formData,
      dataType: "json",
      url: 'form-submit',
      type: "POST",
      beforeSend: function() {
        that.setState({
          user_info: latestUserInfo,
          formSubmissionStatus: 'form-already-submitted'
        });
      }
    });
  }

问题是formSubmissionStatus值似乎没有在handleSubmit中正确更新。我可以单击编辑,填写表单,按提交并查看服务器上的新数据更新,以及新的StaticComponent中的新信息。但我似乎无法通过第二次点击编辑再次加载表单。使用webdev工具,beforeSend回调中的setState似乎没有正确更新formSubmissionStatus状态。

1 个答案:

答案 0 :(得分:2)

第二次单击编辑,并且React呈现交互式组件时,它会看到已存在一个InteractiveComponent,因此它通过更新它的道具和重新渲染来重用它。

在你的例子中,更新它的道具和重新渲染并没有改变它的状态。 componentWillReceiveProps有一个组件生命周期方法,可让您将新Props转移到该状态。

所以,在interactiveComponent上尝试这样的事情。

componentWillReceiveProps: function(nextProps) {
    this.setState({user_info: nextProps.user_info, formSubmissionStatus: nextProps.form_status});
}
相关问题