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

时间:2020-03-15 22:41:05

标签: reactjs semantic-ui-react

我仅出于培训目的而创建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>
    )
}

}

1 个答案:

答案 0 :(得分:1)

反应状态是异步的,因此在setState调用之后访问状态仍将访问状态的当前值,而不是预期的下一个状态。

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

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); 
  }
}