React:无法有条件地更新状态
React: unable to conditionally update state
我有一个函数可以根据从不同组件 (qty) 传递的数量参数计算 "total price",并使用它来显示 div:
calculateTotal(qty) {
var t;
if (qty === 1) {
t = 250 //total = total + 250
}
else if (qty > 1) {
t = (qty * 250); //total = qty * 250
}
else {
t = this.state.total
}
return this.setState( { total: this.state.total + t })
}
它将始终显示上一个 计算而不是当前计算。所以如果我输入1,然后输入2作为数量,第一次输入1没有显示,第二次按2显示的数量是250(应该是500)
如果有人对最佳行动方案有任何建议,我们将不胜感激。
如果有帮助,这是触发它的另一个组件中的函数(他们输入一个数量,它将该数量发送给该函数):
handleChange(event) {
const key = Number(event.key)
if (key === "Backspace") {
this.setState({qty: 0})
this.props.handleTotal(0);
} else {
this.setState({qty: key})
this.props.handleTotal(this.state.qty);
}
}
calculateTotal(qty) {
var t;
if (qty === 1) {
t = 250 //total = total + 250
}
else if (qty > 1) {
t = (qty * 250); //total = qty * 250
}
else {
t = (this.state.total * 2);
}
this.setState( { total: t });
return t;
}
请检查这是否可行!
看来是父组件的handleChange出了问题。您正在调用 setState 然后希望将新值传递给下一个函数,但是 this.state.qty 将在下一行中保持不变,因为 setState 是异步的。
handleChange(event) {
const key = Number(event.key)
if (key === "Backspace") {
this.setState({qty: 0})
this.props.handleTotal(0);
} else {
this.setState({qty: key})
// this.props.handleTotal(this.state.qty); // <-- this will return the old value because setState above isn't done running
this.props.handleTotal(key); // <-- try this instead
}
}
我有一个函数可以根据从不同组件 (qty) 传递的数量参数计算 "total price",并使用它来显示 div:
calculateTotal(qty) {
var t;
if (qty === 1) {
t = 250 //total = total + 250
}
else if (qty > 1) {
t = (qty * 250); //total = qty * 250
}
else {
t = this.state.total
}
return this.setState( { total: this.state.total + t })
}
它将始终显示上一个 计算而不是当前计算。所以如果我输入1,然后输入2作为数量,第一次输入1没有显示,第二次按2显示的数量是250(应该是500)
如果有人对最佳行动方案有任何建议,我们将不胜感激。
如果有帮助,这是触发它的另一个组件中的函数(他们输入一个数量,它将该数量发送给该函数):
handleChange(event) {
const key = Number(event.key)
if (key === "Backspace") {
this.setState({qty: 0})
this.props.handleTotal(0);
} else {
this.setState({qty: key})
this.props.handleTotal(this.state.qty);
}
}
calculateTotal(qty) {
var t;
if (qty === 1) {
t = 250 //total = total + 250
}
else if (qty > 1) {
t = (qty * 250); //total = qty * 250
}
else {
t = (this.state.total * 2);
}
this.setState( { total: t });
return t;
}
请检查这是否可行!
看来是父组件的handleChange出了问题。您正在调用 setState 然后希望将新值传递给下一个函数,但是 this.state.qty 将在下一行中保持不变,因为 setState 是异步的。
handleChange(event) {
const key = Number(event.key)
if (key === "Backspace") {
this.setState({qty: 0})
this.props.handleTotal(0);
} else {
this.setState({qty: key})
// this.props.handleTotal(this.state.qty); // <-- this will return the old value because setState above isn't done running
this.props.handleTotal(key); // <-- try this instead
}
}