【发布时间】:2021-12-24 21:58:42
【问题描述】:
想要提高我对函数式组件中 React 的理解,我看到一些在扩展数组或对象时通过函数传递 seState。当我引用docs 时,我看到了:
与类组件中的
setState方法不同,useState确实 不会自动合并更新对象。你可以复制这个 通过将函数更新器形式与对象传播相结合的行为 语法
所以我试图理解为什么会这样实现:
const [count, setCount] = useState([initialCount]);
setCount([...count, newCount])
当涉及到数组和对象时,这不是首选:
const [count, setCount] = useState([initialCount]);
setCount(prevCount => [...prevCount, newCount])
是首选。在我对答案的研究中,我没有找到关于这个的答案,我已经通读了:
- What is the equivalent of passing an updater to
setStatethat takes(state, props)as an argument to update state, using React Hook? - How to use callback with useState hook in react
- setState with spread operator
我可以确定需要该功能的唯一结论是:
- 可能是由于对象或数组在内存中的存储方式
- 正在传递的数据的大小
为什么当涉及到 useState 中的数组和对象时,它应该使用与常用函数相反的函数来传递?
【问题讨论】:
标签: reactjs use-state react-functional-component