在 setState(); 中递增状态对象值是否有效?没有克隆对象?
Is it valid to increment a state object value inside setState(); without cloning the object?
在不克隆 ingredients
的情况下增加 setState(return {})
中的一些 ingredients
值。可以吗?
state = {
// The object I need to increment its value.
ingredients: {
sugar: 0,
salt: 0,
pepper: 0
},
count: 0
}
addSugarHandler = () => {
this.setState((prevState, props) => {
return {
// Incrementing some `ingredients` value
// inside `setState()` without cloning it.
// Is it OK?
ingredients: prevState.ingredients.sugar + 1,
// I am sure the following is valid
count: prevState.count + 1
};
});
}
您可以像 that.But 那样做,但需要进行一些更正。
应该是这样的。
this.setState((prevState, props) => {
return {
ingredients: {
...ingredients,
sugar: prevState.ingredients.sugar + 1
},
count: prevState.count + 1
};
});
在不克隆 ingredients
的情况下增加 setState(return {})
中的一些 ingredients
值。可以吗?
state = {
// The object I need to increment its value.
ingredients: {
sugar: 0,
salt: 0,
pepper: 0
},
count: 0
}
addSugarHandler = () => {
this.setState((prevState, props) => {
return {
// Incrementing some `ingredients` value
// inside `setState()` without cloning it.
// Is it OK?
ingredients: prevState.ingredients.sugar + 1,
// I am sure the following is valid
count: prevState.count + 1
};
});
}
您可以像 that.But 那样做,但需要进行一些更正。 应该是这样的。
this.setState((prevState, props) => {
return {
ingredients: {
...ingredients,
sugar: prevState.ingredients.sugar + 1
},
count: prevState.count + 1
};
});