useState 钩子,setState 函数.访问先前的状态值 [英] useState hook, setState function. Accessing previous state value
问题描述
这两个是等价的吗?如果不是,哪个最好,为什么?
const [count, setCount] = useState(initialCount);<button onClick={() =>setCount(count + 1)}>+
const [count, setCount] = useState(initialCount);<button onClick={() =>setCount(prevCount => prevCount + 1)}>+
如果下一个状态值依赖于前一个值,如本示例中的增量按钮,最好使用 setState 的函数版本 (setCount(prevCount => prevCount + 1)
).
如果您将 setter 函数传递给回调函数,例如 onChange 或 HTTP 请求响应处理程序,则可能会遇到错误.
举一个明确的例子,在在下面的页面,如果你点击延迟计数器(基本)",然后点击立即计数器",计数只会增加1.但是,如果你点击延迟计数器(功能)",然后是"Immediate Counter",计数最终会加2.
import React, { useState } from "react";从react-dom"导入 ReactDOM;函数计数器(){const [count, setCount] = useState(0);返回 (<div><h1>{count}</h1><button onClick={() =>setTimeout(() => setCount(count + 1), 2000)}>延迟计数器(基本)按钮><button onClick={() =>setTimeout(() => setCount(x => x + 1), 2000)}>延迟计数器(功能)按钮><button onClick={() =>setCount(count + 1)}>立即计数器</button>
);}const rootElement = document.getElementById("root");ReactDOM.render(
Are these two equivalent? If not which is best and why?
const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(count + 1)}>+</button>
const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
If the next state value depends on the previous value, as in this example of an increment button, it's better to use the functional version of setState (setCount(prevCount => prevCount + 1)
).
You can run into errors if you're passing the setter function into a callback function, like an onChange or HTTP Request response handler.
As an explicit example, in the below page, if you click "Delayed Counter (basic)" and then click "Immediate Counter", the count will only increment by 1. However, if you click "Delayed Counter (functional)", followed by "Immediate Counter", the count will eventually increment by 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);
这篇关于useState 钩子,setState 函数.访问先前的状态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!