我对React.js还是很陌生,只是在尝试验证表单时遇到问题。我有以下表单字段和onChange函数:
<AvField type="text" name="name" id="name" placeholder="Name" value={scheduleEvent.name} onChange={this.inputChange} className="form-control-sm" required />
inputChange = (event) => {
const { name, value } = event.target;
console.log(name, value);
let scheduleEvent = {...this.state.scheduleEvent};
console.log(scheduleEvent);
scheduleEvent[name] = value;
console.log(scheduleEvent);
this.setState({scheduleEvent});
console.log(this.state.scheduleEvent);
}
当我输入“ a”时,将获得以下console.log输出:
name a //as expected
{name: ""} //as expected
{name: "a"} //as expected
{name: ""} //this.state.scheduleEvent did not get updated
然后,如果我输入另一个字符,console.log输出如下:
name aa //as expected
{name: "a"} //as expected, but for whatever reason it did not get updated on the first invocation of inputChange
{name: "aa"} //as expected
{name: "a"} // did not get updated
但是,当我提交表单时,this.state.scheduleEvent是正确的。
我也尝试了从React网站链接的这个示例:https://codepen.io/gaearon/pen/VmmPgp?editors=0010那里也存在相同的问题。反正有解决办法吗?
谢谢
答案 0 :(得分:2)
当心setState是异步的!状态更新将发送到待处理的队列中,因此有可能使您返回现有状态。为了保证我们总是访问新近更新的状态,this.setState带有第二个参数,一旦状态被更新,该参数将允许我们链接回调。
将输入更改功能更新为:
inputChange = (event) => {
const { name, value } = event.target;
console.log(name, value);
let scheduleEvent = {...this.state.scheduleEvent};
console.log(scheduleEvent);
scheduleEvent[name] = value;
console.log(scheduleEvent);
this.setState({ scheduleEvent }, () => {
console.log(this.state.scheduleEvent);
});
}