事件摘要:
我单击编辑按钮。
editForm() 在 render() 中使用 this.setState() 和 this.state 显示表单。
上面的 setState() 将 {this.state} 作为我需要显示的值。
一旦我单击表单内的更新按钮,updateMessage() 就会激活,其中 Meteor.call 包含一个回调选项。
这个回调函数有 this.setState() 连接到我上面提到的那个 {this.state}。
那么如何在 Meteor.call() 回调和 setState() 之后显示 {this.state}?
-注意- 将 { this.state } 放入 render() 将在回调后显示。
下面是代码:editMessage () 中的 this.state.show_error_or_noerror 是我需要显示的。
constructor(props) {
super(props);
const messageContent = this.props.messageContent;
const username = this.props.username;
const articleTitle = this.props.articleTitle;
this.state = {
show_error_or_noerror: '',
messageContent: messageContent,
username: username,
articleTitle: articleTitle
};
this.editMessage = this.editMessage.bind(this);
this.updateMessage = this.updateMessage.bind(this);
}
updateMessage(event) {
event.preventDefault();
const messageId = this.props.messageId;
const messageContent = this.refMessage.value.trim();
Meteor.call('message.update', messageId, messageContent, (error) => {
if(error) {
this.setState({show_error_or_noerror: error.reason});
} else {
this.setState({show_error_or_noerror: 'Updated successfully.'});
}
});
}
editMessage(event) {
event.preventDefault();
const messageId = this.props.messageId;
this.setState({
['show_form'+messageId]: <form onSubmit={this.updateMessage}>
<textarea
ref={(textarea) => {this.refMessage = textarea;}}
defaultValue={this.state.messageContent}
/>
<h6>by {this.state.username}</h6>
<h6>Article: {this.state.articleTitle}</h6>
<button type="submit">Update</button>
<button onClick={this.hideForm}>Hide</button>
{this.state.show_error_or_noerror}
</form>
});
}
render() {
const messageId = this.props.messageId;
return (
<span className="message_updator">
<button onClick={this.editMessage}>Edit</button>
{this.state['show_form'+messageId]}
</span>
)
}
}