當我的代碼運行時,它使用舊值來表示興趣,因為它是異步的,如何讓 calcMoney 等待狀態更新?提前致謝
更新這是整個代碼它很可能真的搞砸了,因為我剛剛開始反應,什么應該屬于渲染內部,什么應該在其他地方對我來說仍然是一個謎
import React, { useState } from "react";
function InputForm() {
const [investinit, setInvestinit] = useState("");
const [deposit, setDeposit] = useState("");
const [interest, setInterest] = useState("");
function changeInit(e) {
setInvestinit(parseInt(e.target.value));
console.log(e);
calcMoney();
}
function changeDeposit(e) {
if (e.target.value == "") {
e.target.value = 0;
}
setDeposit(parseInt(e.target.value));
calcMoney();
}
function changeInterest(e) {
setInterest(parseFloat(e.target.value), () =>
console.log(e);
}
function calcMoney() {
var bigArr = [
{ totalAmount: investinit, tottalYield: 0, id: 0, totalMonthly: deposit },
];
var monthlyInterest = interest / 1200 1;
for (var i = 1; i < 13; i = i 1) {
var newTotal =
investinit * Math.pow(monthlyInterest, i)
deposit * ((Math.pow(monthlyInterest, i) - 1) / (monthlyInterest - 1));
var totalMonthly = deposit * i;
var gain = newTotal - (investinit totalMonthly);
bigArr.push({
totalAmount: newTotal,
id: i,
tottalYield: gain,
totalMonthly: totalMonthly,
});
console.log(bigArr);
}
}
return (
<div className="wrapper">
<div className="form-wrap">
<form>
<div className="form-body">
<div className="form-item">
<label>Investment Amount $</label>
<input
type="number"
onChange={changeInit}
value={investinit}
placeholder="Investment Amount (required)"
min="0"
step="100"
required
/>
</div>
<div className="form-item">
<label>Monthly investment $</label>
<input
type="number"
onChange={changeDeposit}
value={deposit}
placeholder="Monthly Deposit (optional)"
min="0"
step="100"
/>
</div>
<div className="form-item">
<label>Annual interest %</label>
<input
type="number"
onChange={changeInterest}
value={interest}
placeholder="Annual interest (required)"
min="0"
step="0.1"
required
/>
</div>
</div>
</form>
</div>
</div>
);
}
export { InputForm };
uj5u.com熱心網友回復:
setState 函式采用可選的回呼引數,可用于在狀態更改后進行更新:
setInterest(parseFloat(e.target.value), () => {
calcMoney();
}
或者,您可以使用 useEffect 并觀察 'interest' 的值,并在它發生變化時執行計算。
useEffect(() => {
calcMoney();
}, [interest]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408308.html
標籤:
