[英]React issue with updating state during re-render
我有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通过道具设置user_info的状态。 再次从道具中将状态的formSubmissionStatus
值分配为初始状态的“待发送形式”。 该组件还具有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() {
// ...
}
});
渲染函数具有一种在提交时调用handleSubmit
的形式。 它还根据表单的提交状态,分配一个userInfo
,将新道具设置为道具中的现有user_info数据,或将状态中的更新信息设置为。
如果状态设置为“要发送的表单”,则render函数还可以呈现表单,否则将呈现StaticComponent。 那是因为它假定表单已提交。
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的工具,它似乎那些在中的setState beforeSend
回调不能正常更新formSubmissionStatus状态。
第二次单击编辑,React渲染了一个交互式组件,它会发现那里已经存在一个InteractiveComponent,因此它将通过更新其props并重新渲染来重用它。
在您的示例中,更新道具并重新渲染不会改变其状态。 有一个组件的生命周期方法componentWillReceiveProps
,给你一个机会,新的传送Props
的状态。
因此,请在您的interactiveComponent
上尝试类似的interactiveComponent
。
componentWillReceiveProps: function(nextProps) {
this.setState({user_info: nextProps.user_info, formSubmissionStatus: nextProps.form_status});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.