这是否意味着我做错了什么?
我以为严格模式是为了帮助你发现副作用.
如果我关闭严格模式,我会正确更新数量(每次点击一次).在严格模式下,每次点击都会更新两次.在本例1中,它说明了在updateItem
中使用Class方法更新数量时,在打开严格模式时每次单击两次的行为:
class ItemModel {
id: number
quantity: number
name: string
constructor(name: string) {
this.id = Math.random()
this.quantity = 1
this.name = name
}
increaseQuantity = () => {
this.quantity = this.quantity + 1
return this
}
decreaseQuantity = () => {
this.quantity = this.quantity >= 2 ? this.quantity - 1 : 1
return this
}
}
....
const [items, setItems] = useState<ItemProps[]>([])
....
const updateItem = (id: number) => {
setItems(items => items.map(item => (item.id === id ? { ...item.increaseQuantity() } : item)))
}
....
<button type="button" onClick={() => updateItem(id)}>+ 1</button>
在updateItem
个中的例2中,使用严格模式,我得到了正确的行为(每次点击更新一次数量):
const updateItem = (id: number) => {
setItems(items => items.map(item => (item.id === id ? { ...item, quantity: item.quantity + 1 } : item)))
}
在这两个示例中,即打开严格模式的示例1和示例2,我向数组返回一个新的更新、非Mutations 对象,那么为什么当我在示例1中使用类方法更新数量时,与在示例2中手动更新数量时,我会得到不同的行为.