useState 钩子,setState 函数。访问以前的状态值
useState hook, setState function. Accessing previous state value
这两个是等价的吗?如果不是哪个最好,为什么?
const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(count + 1)}>+</button>
const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
两个示例均有效且工作原理相同。但是,我怀疑 primitive
与 function
的操作相同,因为 JavaScript
支持 first-class/higher order functions
。这意味着函数像任何其他变量一样受到威胁,允许将它们作为参数传递,将它们分配给变量,并 return 它们在任何其他函数中。
如果下一个状态值取决于前一个值,如本例中的增量按钮,最好使用the functional version of setState (setCount(prevCount => prevCount + 1)
)。
如果将 setter 函数传递给回调函数,例如 onChange 或 HTTP 请求响应处理程序,则可能 运行 出错。
作为一个明确的例子,in the below page,如果你点击"Delayed Counter (basic)"然后点击"Immediate Counter",计数只会增加1。但是,如果你点击"Delayed Counter (functional)",后面跟着"Immediate Counter",计数最终会增加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);
这两个是等价的吗?如果不是哪个最好,为什么?
const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(count + 1)}>+</button>
const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
两个示例均有效且工作原理相同。但是,我怀疑 primitive
与 function
的操作相同,因为 JavaScript
支持 first-class/higher order functions
。这意味着函数像任何其他变量一样受到威胁,允许将它们作为参数传递,将它们分配给变量,并 return 它们在任何其他函数中。
如果下一个状态值取决于前一个值,如本例中的增量按钮,最好使用the functional version of setState (setCount(prevCount => prevCount + 1)
)。
如果将 setter 函数传递给回调函数,例如 onChange 或 HTTP 请求响应处理程序,则可能 运行 出错。
作为一个明确的例子,in the below page,如果你点击"Delayed Counter (basic)"然后点击"Immediate Counter",计数只会增加1。但是,如果你点击"Delayed Counter (functional)",后面跟着"Immediate Counter",计数最终会增加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);