简体   繁体   English

一次操作禁用并重新启用按钮

[英]Disable and re-enable button on single action

I need to disable and re-enable a button during the async call. 我需要在异步调用期间禁用并重新启用按钮。 I am only able to disable it. 我只能将其禁用。 If I add code to re-enable it is ignored. 如果添加代码以重新启用它,则将被忽略。 I acknowledge I may not be asking the right question. 我承认我可能没有问正确的问题。

I have a function with a button "Action": 我有一个带有按钮“动作”的功能:

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

That is called by a React class "Actions": 这被React类称为“ Actions”:

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

That is called by another React class "List": 这被另一个React类“ List”调用:

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

Also in that class is are the following functions: 该类中还有以下功能:

...
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();
    }
  },
...

Here's what the source looks like: 来源如下所示:

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

I can place this.setState(isButtonDisabled: true) at various places in this code and that value makes it to the view and disables the button. 我可以将this.setState(isButtonDisabled: true)放置在此代码中的各个位置,该值会将其显示到视图中并禁用按钮。 However I cannot figure out how to re-enable the button after the work has been done. 但是,我无法弄清楚工作完成后如何重新启用按钮。

If I'm understanding you correctly you want the button to be disabled during async and after async be enabled? 如果我对您的理解正确,那么是否希望在异步过程中以及启用异步后禁用按钮? If that is the case, wherever you are calling the function that makes the api call, you just need to chain a .then(() => this.setState(isButtonDisabled: false) and that will update the state as soon as response has been received from api call. also if you aren't using es6 just make sure to set this to a variable above the api call to ensure its scoped properly for setState 如果是这种情况,无论您在哪里调用进行api调用的函数,您.then(() => this.setState(isButtonDisabled: false)需要链接.then(() => this.setState(isButtonDisabled: false) ,它将在响应发生后立即更新状态从API调用已收到。如果你还没有使用ES6只要确保设置this API调用高于变量,以确保其正常范围的对的setState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM