简体   繁体   English

为什么状态在这里没有得到更新?

[英]Why state is not getting updated here?

import { useEffect } from "react";
import { useRef } from "react";
import { useState } from "react";

const Button = () => {

    const [counter, setCounter] = useState(0)
    const btnRef = useRef();


    useEffect(() => {
        btnRef.current.addEventListener('click', function () {
            setCounter(counter => 1);
            console.log('counter ', counter);
        })
    },[])

    return (
        <button ref={btnRef}>Click Me</button>
    )
}

export default Button;

On each click of button, console shows only '0', why setCounter is not updating the state here ?每次单击按钮时,控制台只显示 '0',为什么 setCounter 不在这里更新状态?

import { useEffect } from "react";
import { useRef } from "react";
import { useState } from "react";

const Button = () => {
  const [counter, setCounter] = useState(0);
  const btnRef = useRef();

  console.log(counter)

  useEffect(() => {
    btnRef.current.addEventListener("click", function () {
      setCounter((counter) => 1);
    });
  }, []);

  return <button ref={btnRef}>Click Me</button>;
};

Thanks to @Yousaf for explaining the closure issue in comments:感谢@Yousaf 在评论中解释关闭问题:

You also have a problem because of closure of the event listener function over the initial value of the counter state由于在计数器状态的初始值上关闭了事件侦听器函数,因此您也遇到了问题

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

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