0

事件摘要:
我单击编辑按钮。
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>
    )
  }
}
4

1 回答 1

0

要在流星中实现反应性,请创建一个 Tracker.dependency 对象并让您的渲染依赖它(ref)。

在构造函数中创建依赖项

var dep = new Tracker.Dependency;

让你的渲染依赖它

dep.depend();

并在你的 setState 函数中调用它

dep.changed();
于 2017-03-09T07:03:52.180 回答