无法在状态中设置输入字段值?

Can not set input field values in state?

我正在创建 React 应用程序只是为了培训目的。我无法在表单提交按钮上设置值。 如果我开始输入值,这些值将存储在名称和价格中,但是当我单击提交按钮时,它不会在 formData 中设置名称和价格。

如果我尝试在 formData 中设置值。

onChange={(e) => this.setState({formData:{
price: e.target.value
})}

像上面一样,我不能输入字段。

你可以检查我使用控制台检查发生了什么。

import React from 'react';
import { Button, Form, Icon, Modal } from 'semantic-ui-react';

export default class ProductForm extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        showCreateForm: false,
        addOrdit:false,
        id: "",
        name: "",
        price: "",
        formData: {},
        record: {}
    };
    if (props.isAddProduct){
        this.state.showCreateForm = props.isAddProduct;
    }
    else if (props.singleProduct) {
        this.state.id = props.singleProduct.product.productId;
        this.state.name = props.singleProduct.product.name;
        this.state.price = props.singleProduct.product.price;
        this.state.record = props.singleProduct.product;
        this.state.showCreateForm = props.singleProduct.isEditProduct;
        this.state.addOrdit = props.singleProduct.isEditProduct;
        console.log(this.state.name)

    }else if(props.closeForm){
        this.state.showCreateForm = props.closeForm;
    }

}

handleSubmit = event => {
    event.preventDefault();

    if(this.state.addOrdit){

        this.setState({
            record: {
                productId: this.state.id,
                name: this.state.name, 
                price: this.state.price
            }
        });
    this.props.onAddFormSubmit(this.state.record);

    }else{
        console.log("In submit befor set "+this.state.name)
        this.setState({
            formData: {
                name: this.state.name, 
                price: this.state.price
            }
        });
        console.log("In submit after set"+this.state.formData)
        this.props.onAddFormSubmit(this.state.formData);
    }
}

//On cancel button click close form
closeCreateForm = () => {
    this.setState({ showCreateForm: false })
    this.props.onFormControl();
}

//Open form
openCreateCustomer = () => {
    this.setState({ showCreateForm: true })
}

render() {

    let formTitle;
    let buttonName;
    if (this.state.addOrdit) {
        formTitle = "Edit Product";
        buttonName = "Edit";
    } else {
        formTitle = "New Product";
        buttonName = "Create";
    }

    return (
        <div>
            <Modal size='small' 
            closeOnTriggerMouseLeave={false} 
            open={this.state.showCreateForm}>
                <Modal.Header>
                    {formTitle}
                </Modal.Header>
                <Modal.Content>
                    <Form onSubmit={this.handleSubmit}>

                        <Form.Field>
                            <label>Name</label>
                            <input type="text" placeholder='Name' name="name"
                                value={this.state.name}
                                onChange={(e) => this.setState({name: e.target.value})} />
                        </Form.Field>

                        <Form.Field>
                            <label>Address</label>
                            <input  placeholder='Price' name="price"
                                value={this.state.price}
                                onChange={(e) => this.setState({price: e.target.value})} />
                        </Form.Field>

                        <br />
                        <Button type='submit' icon labelPosition='right'  
                            floated='right' color='green'>
                                <Icon name='check'/>
                                {buttonName}
                            </Button>
                        <Button floated='right' 
                        onClick={this.closeCreateForm} color='black'>
                            Cancel
                        </Button>
                        <br />
                    </Form>

                </Modal.Content>
            </Modal>

        </div>
    )
}

}

React 状态是异步的,所以在 setState 调用之后访问状态仍然会访问状态的 current 值和 not 预期的 下一个 状态。

一个小的重构允许您设置状态 提交相同的 value/object。首先构造要保存到状态的对象,然后更新状态并提交。

setState 也可以带一个可选的第二个参数,它是保证在 状态更新后调用的回调函数,因此您可以在那里控制台日志状态更新而是为了记录下一个状态。

handleSubmit = event => {
  event.preventDefault();

  if (this.state.addOrdit) {
    const newRecord = {
      productId: this.state.id,
      name: this.state.name, 
      price: this.state.price
    };

    this.setState({ record: newRecord });
    // submit same new record saved to state
    this.props.onAddFormSubmit(newRecord);
  } else {
    const formData = {
      name: this.state.name, 
      price: this.state.price
    };

    console.log("In submit before set " + this.state.name);
    this.setState({ formData }, () => {
      // now see updated state!!
      console.log('setState callback', this.state.formData);
    });

    // still old data
    console.log("In submit after set" + this.state.formData);
    // submit same new form data saved to state
    this.props.onAddFormSubmit(formData); 
  }
}