gpt4 book ai didi

javascript - 第一次提交表单时为空值

转载 作者:行者123 更新时间:2023-11-29 18:45:54 25 4
gpt4 key购买 nike

我有以下代码,旨在将输入馈送到 ToggleForm 组件(这是一个表单)并将其存储在 employeeData 状态。但是,问题是每当我在执行后第一次按下 ToggleForm 的提交按钮时,"" 值首先存储在 employeeData 状态,只有在我第二次单击提交按钮后,表单中输入的数据才会到达 employeeData

这一定是个小错误。但我无法弄清楚。

import React from "react";
import ToggleForm from "./ToggleForm";
let employee = "";
class Home extends React.Component {
constructor(){
super();
this.state = {
employeeData: ""
};
}

addEmployee(e) {
e.preventDefault();
let name = e.target.name.value;
let address = e.target.address.value;
let salary = e.target.salary.value;
this.setState({
employeeData: [...this.state.employeeData, { name, address, salary }]
});
employee = [...this.state.employeeData];
console.log(employee);
}

render() {
return (
<div className="container">
<ToggleForm addEmployee={this.addEmployee.bind(this)}/>
</div>
);
}
}

export default Home;

这是 ToggleForm 组件:

import React from 'react';

class ToggleForm extends React.Component {
render(){
return(<div>
<br/>
<h3>Add a new employee</h3>
<hr/>
<form className="form-group" onSubmit = {this.props.addEmployee}>
<input className="form-control" type="text" name="name" placeholder="Name of the employee"/><br/>
<input className="form-control" type="text" name="address" placeholder="Address of the employee"/><br/>
<input className="form-control" type="text" name="salary" placeholder="Salary of the employee"/><br/>
<input type="submit" className="btn btn-primary"/>
</form>
</div>)
}
}

export default ToggleForm;

最佳答案

setStateasync 幸运的是 accepts an optional callback .使用回调,您可以访问最新的状态值。

this.setState({
employeeData: [...this.state.employeeData, { name, address, salary }]
}, () => {
employee = [...this.state.employeeData];
});

关于javascript - 第一次提交表单时为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53968858/

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