首页 文章

Meteor-React:Meteor.call回调完成后如何在setState内的状态重新渲染?

提问于
浏览
0

活动摘要:
我点击编辑按钮 .
editForm()在render()中使用this.setState()和this.state显示表单 .
上面的setState()将
作为我需要显示的值 .
一旦我单击表单内的更新按钮,updateMessage()就会激活,其中Meteor.call包含一个回调选项 .
这个回调函数有this.setState()连接到我上面提到的
.

那么如何在Meteor.call()回调和setState()之后显示

-note-将置于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>
    )
  }
}

1 回答

  • 0

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

    在构造函数中创建依赖项

    var dep = new Tracker.Dependency;
    

    你的渲染依赖于它

    dep.depend();
    

    并在您的setState函数中调用它

    dep.changed();
    

相关问题