[英]setState inside a method one step behind
我正在做一個React項目,該項目涉及顯示一個值(DisplayValue),然后將該值存儲在狀態中,以便以后使用。 問題是狀態總是落后一步(例如,如果displayValue為“ 12”,則值僅為1)。 我需要兩個值都相同。 是因為setState是異步的嗎? 我該如何解決?
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)
})
};
Codepen: https ://codepen.io/HernanF/pen/jXzPJp
您正在打破基本的React規則 :永遠不要通過將對象傳遞給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)
}
);
}
代碼似乎有問題,不是React
value1 = parseFloat(displayValue);
應該
value1 = parseFloat(displayValue + String(digit));
與displayValue
相同
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.