AddEventListener 看不到范围

AddEventListener doesn't see scope

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

比行为的原因是什么?

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

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

您遇到了关闭问题。

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

例如:

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

在您的第二次渲染中,您创建了一个函数 showCount,您将其固定为 count = 2。

在您的 3 渲染中,您创建了一个固定计数 = 3 的函数 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 可以从当前计数值更新..

下面是重构代码...