I´m working on a React project, which involves displaying a value (DisplayValue) and then storing that value inside state so that I can use it later. Problem is state is always one step behind (for instance, if displayValue is "12", value is just 1). I need both values to be the same. Is it because setState is async? How can I fix it?
inputDigit(digit) {
const {
pendingOperation,
displayValue
} = this.state;
if (pendingOperation) {
this.setState({
displayValue: String(digit),
pendingOperation: false
})
}
value1 = parseFloat(displayValue);
this.setState({
displayValue: displayValue === "0" ? String(digit) : displayValue + String(digit),
value: value1
}, () => {
console.log(this.state.value)
})
};
答案 0 :(得分:2)
您要破坏a fundamental React rule:切勿通过将对象传递到setState
来基于现有状态设置状态。而是使用回调形式,并使用回调形式接收的状态对象。您可能还想打setState
一次,而不是(可能)打两次。
因此,您希望在更新回调中进行如下更改:
inputDigit(digit) {
this.setState(
({pendingOperation, displayValue}) => {
const newState = {};
if (pendingOperation) {
newState.displayValue = String(digit);
newState.pendingOperation = false;
}
newState.value = parseFloat(displayValue);
// Not sure what you're trying to do with the second setState calls' `displayValue: displayValue === "0" ? String(digit) : displayValue + String(digit),`...
return newState;
},
() => {
console.log(this.state.value)
}
);
}
答案 1 :(得分:0)
There seem to be a problem in the code, not React
value1 = parseFloat(displayValue);
should be
value1 = parseFloat(displayValue + String(digit));
The same as for displayValue