首页 > 解决方案 > 为什么我必须在反应的事件处理程序中使用箭头函数?

问题描述

function ButtonIncrement(){
    const [count,setCount] = useState(0);
    render(){
        <div>
        <h3>
           <button onClick={() => setCount(count+1)}>Increment me for fun</button>
           <p>Count: {count} </p>
        </h3>
        </div>
    }
}

在这个 onClick 按钮中,为什么简单的 putonClick={setCount(count+1)}不起作用?我收到一个无限循环,看来我必须使用箭头函数。我怀疑它与“这个”有关。

标签: javascriptreactjsevent-handlingarrow-functions

解决方案


如果没有箭头功能,每次单击按钮都会再次呈现页面,这会设置状态,然后再次呈现,并设置状态,然后再次呈现。无限循环箭头函数在安装/更新时重新创建该函数一次。

在这里阅读更多https://reactjs.org/docs/faq-functions.html


推荐阅读