gpt4 book ai didi

reactjs - 延迟一个字符更新状态

转载 作者:行者123 更新时间:2023-12-05 06:57:05 24 4
gpt4 key购买 nike

我有 4 个输入字段,我在其中输入金额,并根据该金额获得费率。

场景:当用户填写字段时,例如在 input1 中输入 20000,比率必须为 116.04,但用户得到的不是 11.60。所以有 1 个字符的明显延迟,只要我在 input2 字段中输入 0,我就会得到正确的速率,即 116.04这对我来说是 Not Acceptable ,因为我总共有 4 个字段,而且数字总是不同的。我该如何解决???这是我的状态:

 this.state = {
input: {
amount: '20000',
inputField1: '',
inputField2: '',
inputField3: '',
inputField4: '',
...window.input,
},

这些是我的输入字段:

 <Input className="col-8"
value={this.state.input.inputField1}
onChange={(event) => {
this.updateInputField("inputField1", event.target.value);
}}/>
<Input className="col-8"
value={this.state.input.inputField2}
onChange={(event) => {
this.updateInputField("inputField2", event.target.value);
}}/>
<Input className="col-8"
value={this.state.input.inputField3}
onChange={(event) => {
this.updateInputField("inputField3", event.target.value);
}}/>
<Input className="col-8"
value={this.state.input.inputField4}
onChange={(event) => {
this.updateInputField("inputField4", event.target.value);
}}/>

这些是我的方法:

updateInput = (key, value) => {
let input = {...this.state.input};
input[key] = value;
window.input = input;
this.calculate(input);
};

updateInputField= (key, value) => {
let {input} = this.state;
let sum = +input.inputField1 + +input.inputField2 + +input.inputField3 + +input.inputField4
input[key] = value;
this.setState({input});
window.input = input;
this.updateInput("amount",sum)// this is where I am getting the delay
};

我正在尝试使用此状态计算总金额:

<p>{this.state.input.amount}</p>

最佳答案

在您的 updateInputField 函数中 - 不要在 更新 input[key] 之前计算 sum,而是尝试更新更新input[key]然后计算sum。像这样:

// first, update 'input' with the new value
input[key] = value;

// next, calculate the new sum
let sum = +input.inputField1 + +input.inputField2 + +input.inputField3 + +input.inputField4

您看到的“延迟”是由于您的代码遵循以下顺序:

  1. 从状态中获取旧的输入
  2. 计算旧输入值的总和
  3. value 更新 input(在当前 key 处)
    • 这需要是#2,而不是#3!
  4. 在状态中设置更新的输入
  5. 调用 this.updateInput

因此您的新 updateInputField 函数将如下所示:

updateInputField= (key, value) => {
let {input} = this.state;
// first, update 'input' with the new value
input[key] = value;

// next, calculate the new sum
let sum = +input.inputField1 + +input.inputField2 + +input.inputField3 + +input.inputField4

this.setState({input});
window.input = input;
this.updateInput("amount",sum)
};

关于reactjs - 延迟一个字符更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64981473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com