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

React issue with updating state during re-render

本文关键字:问题 状态 更新 新渲染      更新时间:2023-09-26

我有2个组件,一个静态组件和一个交互式组件。静态组件显示用户的信息。它有一个链接来编辑信息。该链接有一个 onClick 触发handleEditClick函数。这会将静态组件替换为具有表单的交互式组件。

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);
  },
})

交互组件从道具设置user_info的状态。它还将状态的formSubmissionStatus值分配为"待发送的表单"初始状态,再次来自道具。该组件还有一个handleSubmit函数,显然还有一个渲染函数。

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() {
    // ...
  }
});

呈现函数有一个在提交时调用handleSubmit的表单。它还分配一个userInfo,该将新 props 设置为道具中的现有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 调用之前,它会将用户信息的状态更新为最新数据,并更新 formSubmitStatus 值。

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'
        });
      }
    });
  }

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

第二次单击编辑时,React 渲染了一个交互式组件,它看到那里已经有一个现有的 InteractiveComponent,因此它通过更新它的 props 和重新渲染来重用它。

在您的示例中,更新它的 props 和重新渲染不会改变它的状态。有一种用于componentWillReceiveProps的组件生命周期方法,它使您有机会将新Props转移到状态。

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

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