React / React Native:无法使用先前状态的键设置状态?
React / React Native: can't setState using key from previous state?
努力了解这两个片段之间的区别:
未设置状态
handleAddItemToCart = (item) => {
this.setState((state) => {
const { cartItems } = state;
item.quantity = 1;
cartItems.push(item);
return { cartItems };
});
}
状态已设置
<...>
return { cartItems: [...cartItems] }
这对我来说实际上不是问题,因为我正在使用它,但我真的很想了解这里发生了什么 - 我误解了什么?
因为通过推送到数组,你改变了之前和当前的状态。虽然 React 不关心,但 shouldComponentUpdate
会关心,因为它无法决定当前状态是否不同于之前的状态,因为你改变了两者。
shouldComponentUpdate(nextProps, nextState) {
// does return false, although you mutated the state
return nextState.items !== this.state.items;
}
也就是说,防弹、完全不可变的方法是:
this.setState({ cardItems }) => ({ cartItems: [...cardItems, { ...item, quantity: 1 }] }));
努力了解这两个片段之间的区别:
未设置状态
handleAddItemToCart = (item) => {
this.setState((state) => {
const { cartItems } = state;
item.quantity = 1;
cartItems.push(item);
return { cartItems };
});
}
状态已设置
<...>
return { cartItems: [...cartItems] }
这对我来说实际上不是问题,因为我正在使用它,但我真的很想了解这里发生了什么 - 我误解了什么?
因为通过推送到数组,你改变了之前和当前的状态。虽然 React 不关心,但 shouldComponentUpdate
会关心,因为它无法决定当前状态是否不同于之前的状态,因为你改变了两者。
shouldComponentUpdate(nextProps, nextState) {
// does return false, although you mutated the state
return nextState.items !== this.state.items;
}
也就是说,防弹、完全不可变的方法是:
this.setState({ cardItems }) => ({ cartItems: [...cardItems, { ...item, quantity: 1 }] }));