简体   繁体   English

反应点击处理程序无法正常工作

[英]react click handler does not work properly

there is a click handler , with 2 statements, and just one of them works, and when I comment out one of them , the other one works properly.有一个点击处理程序,有 2 个语句,只有其中一个可以工作,当我注释掉其中一个时,另一个可以正常工作。 the setShowDeleteConfirm is local state . setShowDeleteConfirm 是本地状态。 and the setDeleteModal is context.而 setDeleteModal 是上下文。 why this happens?.为什么会这样?。 tanx in advance.提前tanx。

<FaTrashAlt onClick={(e) => {
          setShowDeleteConfirm(!showDeleteConfirm);
          setDeleteModal(!deleteModal);
          e.stopPropagation();
          
          }}/> 

The reason for this is that setState() is asynchronous in Nature, we do not know when one will be executed.这样做的原因是setState()本质上是异步的,我们不知道什么时候会执行。 That's why this happens.这就是为什么会发生这种情况。

Suppose you have these two set Functions.假设你有这两个集合函数。

  setShowDeleteConfirm(!showDeleteConfirm);
  setDeleteModal(!deleteModal);

When the setShowDeleteConfirm(!showDeleteConfirm);setShowDeleteConfirm(!showDeleteConfirm); starts to execute, we cannot predict when it would update the state, as this is asynchronous in nature, the same goes with other case.开始执行,我们无法预测它何时会更新状态,因为这本质上是异步的,其他情况也是如此。 Cheers !!!干杯!!!

One quick solution I feel is to use callback within the Hook.我觉得一个快​​速的解决方案是在 Hook 中使用回调。

<FaTrashAlt onClick={(e) => {
          setShowDeleteConfirm( (prevState) =>{
               return {
                    showDeleteConfirm:!prevState
               }
           } );
          setDeleteModal( (prevState) => {
                return{
                deleteModal:!prevState
               });
           }
          e.stopPropagation(); // I feel this should not be used, it has no purpose here.
          
          }}/> 

When you are updating the state based on previous value it is always better to use the functional pattern.当您根据先前的值更新状态时,最好使用功能模式。 This helps us with a predictable value for the previous state.这有助于我们为以前的状态提供可预测的值。

 <FaTrashAlt onClick={(e) => {
          setShowDeleteConfirm( showDeleteConfirm => !showDeleteConfirm);
          setDeleteModal( deleteModal => !deleteModal);
          e.stopPropagation();
          
          }}/>   

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

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