我们还需要在 React 钩子中使用函数式 setState 方式吗? [英] Do we still need functional setState way in react hooks?
本文介绍了我们还需要在 React 钩子中使用函数式 setState 方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
const [count, setCount] = useState(0);
const handleClick = () =>
setCount(prevCount => {
return prevCount + 1;
});
const [count, setCount] = useState(0);
const handleClick = () => setCount(count + 1);
来自基于类的组件背景,它成为我们使用函数式setState
的习惯.我想知道我们是否还需要在功能钩子中依赖 prevState ?还是当前状态总是可信"且最更新"?
Coming from class-based component background, it becoming a habit where we use functional setState
. I'm wondering if do we still need to rely on prevState in functional hooks? Or the current state is always "trustable" and most "updated"?
推荐答案
是,行为类似.
React 正在批处理更新调用.写作时:
React is batching the updates calls. When Writing:
const handleClick = () => setCount(count + 1)
handleClick()
handleClick()
handleClick()
状态中的 count
将为 1
写作时:
const handleClick = () =>
setCount(prevCount => {
return prevCount + 1;
});
handleClick()
handleClick()
handleClick()
状态中的 count
将为 3
这篇关于我们还需要在 React 钩子中使用函数式 setState 方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文