首次提交表单时为空值

时间:2018-12-29 10:51:47

标签: javascript reactjs

我有以下代码,旨在将输入馈送到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;

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

由于setState是异步的,因此在更改父组件之前,需要在文本更改时在组件Toggle表单中设置setState。

例如:

<input
onChange={this.handleChange}
className="form-control"
type="text"
name="name"
value={this.state.name}
placeholder="Name of the employee"
/>
<br />

功能handleChange:

 handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
    console.log(e.target.value)
  };

然后将其发送给父项:

 handleSubmit = e => {
    e.preventDefault();
    const { name, address, salary } = this.state;
    this.props.addEmployee({ name, address, salary });
  };

在此处检查我的代码:https://codesandbox.io/s/ww5331jrxl

答案 2 :(得分:0)

您的组件中几乎没有基本更正: 用户super();在this.setState();

之前的构造函数中

如果您不使用this.state.employeeData,请不要将其设置为状态。

如果设置状态,则将在@Andy所描述的回调函数中获取employeeData,或者可以使用以下代码:

employee = [...this.state.employeeData, { name, address, salary }]