【发布时间】:2021-10-17 17:54:36
【问题描述】:
此代码生成 React 错误 301:https://reactjs.org/docs/error-decoder.html/?invariant=301
const [count, setCount] = useState(0)
return <>
<p>{count}</p>
<button onClick={setCount(count + 1)} >Increment count by 1</button>
</>
但如果我在匿名函数中运行setCount 函数,我不会:
return <>
<p>{count}</p>
<button
onClick = {() => {
setCount(count + 1)
}}
>Increment count by 1</button>
</>
有人知道为什么吗?
【问题讨论】:
-
由于在 onClick 函数中调用了 setCount,这会导致状态值不断变化并重新渲染。您必须将 onClick 函数内的函数分配给函数。就像第二次使用一样。
标签: reactjs state use-state anonymous-function inline-functions