【问题标题】:Disable and re-enable button on single action在单个操作上禁用和重新启用按钮
【发布时间】:2017-01-17 19:50:16
【问题描述】:

我需要在异步调用期间禁用和重新启用按钮。我只能禁用它。如果我添加代码以重新启用它会被忽略。我承认我可能没有问正确的问题。

我有一个带有“操作”按钮的功能:

<button className={`doFoo${buttonClasses[type]} ${type}`} onClick={onClick} disabled={isButtonDisabled}>

由 React 类“Actions”调用:

<Action type="like" onClick={onLike} isButtonDisabled={isButtonDisabled} />

这是由另一个 React 类“List”调用的:

<Actions onLike={this.handleLike} onDislike={this.handleDislike} isButtonDisabled={isButtonDisabled}/>

该类中还有以下功能:

...
thumbsUp() {
    const {
      ...
    } = this.props;
    const {
      ...
    } = this.state;

    this.setState({ wasLiked: true, viewProfile: false }, () => {
      setTimeout(doThumbsUp, ACTION_CONFIRMATION_ANIMATION_TIMEOUT);
    });

    function doThumbsUp() {
      thumbsUp({
        index: activeIndex,
        id: profiles[activeIndex].id
      });
    }
  },

  handleLike() {
    const { showThumbsUpConfirmation } = this.props;

    if (showThumbsUpConfirmation) {
      this.showThumbsUpConfirmationModal();
    } else {
      this.thumbsUp();
    }
  },
...

源代码如下:

export function thumbsUp({ id, ... }) {
  return api.post(`${API.ENDPOINTS.FOO}/${id}/thumbs_up`, {
   ...
  });
}

我可以将this.setState(isButtonDisabled: true) 放置在这段代码的不同位置,该值会显示在视图中并禁用按钮。但是我不知道如何在工作完成后重新启用按钮。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 flux alt.js


    【解决方案1】:

    如果我对您的理解正确,您希望在异步期间和启用异步之后禁用该按钮?如果是这种情况,无论您在哪里调用进行 api 调用的函数,您只需要链接一个 .then(() =&gt; this.setState(isButtonDisabled: false) 并且一旦从 api 调用收到响应就会更新状态。另外,如果您不使用 es6,请确保将 this 设置为 api 调用上方的变量,以确保其范围适用于 setState

    【讨论】:

      猜你喜欢
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 2014-09-27
      • 1970-01-01
      • 2016-03-20
      • 1970-01-01
      相关资源
      最近更新 更多