【发布时间】:2022-01-14 19:10:56
【问题描述】:
当我的代码运行时,它使用旧值来表示兴趣,因为它是异步的,如何让 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 };
【问题讨论】:
-
很可能应该在渲染函数中调用 calcMoney 并从状态中直接访问 'insterest'。您能否分享更多代码以查看全貌?
-
我贴出了整个代码
-
'calcMoney' 函数除了 console.log 什么都不做?
-
它确实创建得有点低,我只需要知道当时的事件
-
然后使用“useEffect”从 Phobos 获得第二个答案,并从 changeDeposit 函数中删除 calcMoney 调用,应该没问题 :)
标签: reactjs async-await