我有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