作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我见过一些 React 应用程序使用 useImmer
作为 Hook 而不是 useState
.我不明白什么useImmer
提供 useState
才不是。
使用 useImmer
有什么好处?过度使用官方useState
?
最佳答案
简而言之, immer 有助于您改变嵌套/复杂数据结构的方式。看看这2种方式:
考虑以下对象:
const [product, updateProduct] = useState({
name: "Product 1",
SKU: "SKU-001",
availability: 30,
stock: [
{
id: 1,
store: "Store 1",
quantity: 10
},
{
id: 2,
store: "Store 2",
quantity: 20
}
]
});
为了操作它,您应该传递整个对象并覆盖您想要更新/更改的属性:
updateProduct({ ...product, name: "Product 1 - Updated" })
但是,如果您使用“useImmer”,您可以发送您想要更改的唯一部分,而 immer 本身将处理引擎盖下的其余部分。
const [product, updateProduct] = useImmer({
name: "Product 1",
SKU: "SKU-001",
availability: 30,
stock: [
{
id: 1,
store: "Store 1",
quantity: 10
},
{
id: 2,
store: "Store 2",
quantity: 20
}
]
});
所以要更新:
updateProduct((draft) => {
draft.name = "Product Updated" };
})
当您处理复杂的结构时它确实更有意义,假设您想更改“Stock”数组中的第二个对象,那么您可以使用:
updateProduct((draft) => {
draft.stock[1].quantity = 30;
})
关于reactjs - useState 和 useImmer 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61669930/
我见过一些 React 应用程序使用 useImmer 作为 Hook 而不是 useState .我不明白什么useImmer提供 useState才不是。 使用 useImmer 有什么好处?过度
我是一名优秀的程序员,十分优秀!