我有2个组件,一个StaticComponent和一个InteractiveComponent。 StaticComponent显示用户的信息。它有一个链接来编辑 信息。该链接有一个关闭handleEditClick
功能的onClick。这将使用具有表单的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函数,显然是渲染函数。
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数据或来自状态的更新信息。
如果状态设置为'要发送的表单',则呈现函数也会呈现该表单,否则将呈现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工具,看起来像beforeSend
回调中的setState没有正确更新formSubmissionStatus状态。
+1;一个更好的解决方案是从'StaticComponent'内部移除'React.render'调用,并且使'StaticComponent'和'InteractiveComponent'成为某个父组件的子节点,它决定了何时渲染它们。 –
同意。这是一个更清洁的架构,更多的是React想要它的组件一起工作的方式。 – Crob