这两个相等吗?如果不是,哪个最好,为什么?
const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(count + 1)}>+</button>
const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
如果下一个状态值取决于前一个值(如本例中的增量按钮),则最好使用setState 的函数版本 https://reactjs.org/docs/hooks-reference.html#functional-updates (setCount(prevCount => prevCount + 1)
).
如果将 setter 函数传递到回调函数(例如 onChange 或 HTTP 请求响应处理程序)中,则可能会遇到错误。
作为一个明确的例子,,如果您单击“延迟计数器(基本)”,然后单击“立即计数器”,则计数只会加 1。但是,如果您单击“延迟计数器(功能)”,然后单击“立即计数器”,则计数将增加 1。最终增加2。
import React, { useState } from "react";
import ReactDOM from "react-dom";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
Delayed Counter (basic)
</button>
<button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
Delayed Counter (functional)
</button>
<button onClick={() => setCount(count + 1)}>Immediate Counter</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)