问题描述
这两个等价吗?如果不是,那是最好的,为什么?
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>
推荐答案
如果下一个状态值取决于上一个值,如此示例中的增量按钮,最好使用 setState的功能版本( setCount(prevCount => prevCount + 1)
)
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)
).
如果将setter函数传递给回调函数(例如onChange或HTTP Request响应处理程序),则可能会出错.
You can run into errors if you're passing the setter function into a callback function, like an onChange or HTTP Request response handler.
作为一个明确的示例,在在下一页中,如果您单击延迟计数器(基本)",然后单击立即计数器",则计数只会增加1.但是,如果您单击延迟计数器(功能性)",然后单击立即计数器",该计数最终将增加2.
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函数.访问以前的状态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!