繁体   English   中英

AddEventListener 没有看到 scope

[英]AddEventListener doesn't see scope

当我使用 OnClick 设置处理程序时,它工作正常,并且 console.log 始终使用实际的 state。 但是当我使用 AddEventListener 时,它只工作一次,然后使用旧的 state。

比行为的原因是什么?

查看链接https://codesandbox.io/s/blazing-star-wf3c9?file=/src/App.js

PS使用 [count] 作为 useEffect 依赖修复它,但它只是每次创建新的侦听器,不要认为这样做的正确方法

你有一个关闭问题。

事实上,在每次渲染中,您的组件都会创建一个新的 function showCount,您已修复了计数。

举个例子:

在第一次渲染中,您创建了一个 function showCount,您将其固定为 1。

在您的第二次渲染中,您创建了一个固定计数 = 2 的 function showCount。

在您的 3 渲染中,您创建了一个固定计数 = 3 的 function showCount。

问题是当您的计数发生这样的变化时,您并没有更改显示计数。

useEffect(() => {
    let buttonShow = document.querySelector(".buttonShow");
    buttonShow.addEventListener("click", showCount, true);
    return () => {
      buttonShow.removeEventListener("click", showCount, true);
    };
  }, [count]); 

您可以看到日志计数 2,因为使用增量时计数的引用不会改变。

我认为最好的解决方案是您使用组件 class:

import React from "react";

    class CounterAddEvent extends React.PureComponent {
      state = {
        count: 1
      };
      componentDidMount() {
        let buttonShow = document.querySelector(".buttonShow");
        buttonShow.addEventListener("click", this.showCount, true);
      }
      componentWillUnmount() {
        let buttonShow = document.querySelector(".buttonShow");
        buttonShow.removeEventListener("click", this.showCount, true);
      }
      increaseCount = () => {
        this.setState({ count: this.state.count + 1 });
      };
      showCount = () => {
        console.log(this.state.count);
      };
      render() {
        return (
          <div>
            <button onClick={this.increaseCount} className="input">
              increase
            </button>
            <button>{this.state.count}</button>
            <button className="buttonShow">Show console</button>
          </div>
        );
      }
    }
    export default CounterAddEvent;

错误来自设置“useState(1)”,这将始终在实现“++count”之前将值“count”重新初始化为 1;

所以我使用的简单技巧是将 useState(1) 重构为 useState(x).. 这样 x 就可以从当前计数值更新..

下面是重构的代码...

在此处输入图像描述

暂无
暂无

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

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