【问题标题】:How to use multiple or two state values in one component or class file in react JS?reactjs中如何在一个组件或类文件中使用多个或两个状态值?
【发布时间】:2020-06-19 14:47:59
【问题描述】:

我正在尝试使用状态来隐藏语义 UI 模型表单,并将 JSON 传递给客户类以添加新客户。我能够传递值,但最终只有一个值。

当我开始输入名称时,在控制台面板中,第一个字符名称为空“”,第二个字符有单个“a”

在地址

点击创建按钮

当我点击创建按钮时,名称为空“”并且地址具有价值。

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

export default class AddCustomer extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        showCreateForm:false,
        formData:{
            name: '',
            address: ''
        }
    }
    this.handleChangeName = this.handleChangeName.bind(this);
    this.handleChangeAddress = this.handleChangeAddress.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
}

handleChangeName(event) {
    const value = event.target.value;

    console.log(value);

    this.setState({formData:{name:value}});

    //when i go to add input the formData is still empty name is empty.
    //name: ""
    //address: ""
    console.log(this.state.formData);
}

handleChangeAddress(event) {
    const value = event.target.value;
    console.log(value);
    this.setState({formData:{address:value}});

    //name: "ram" but now there is no address in formData
    console.log(this.state.formData);
}

handleSubmit(event) {
    event.preventDefault();

    ////address: "aaaaa" now there no name in formData
    console.log(this.state.formData);

    this.setState({formData:{
        name:this.state.name, address:this.state.address
    }});
    this.props.onAddFormSubmit(this.state.formData);
}

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

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

render() {

    return (
        <div>
            <Modal closeOnTriggerMouseLeave={false} trigger={
                <Button color='blue' onClick={this.openCreateCustomer}>
                    New Customer
        </Button>
            } open={this.state.showCreateForm}>
                <Modal.Header>
                    Create customer
    </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 = {this.handleChangeName}/>
                        </Form.Field>

                        <Form.Field>
                            <label>Address</label>
                            <input type="text" placeholder ='Address' name = "address"
                                value = {this.state.address}
                                onChange = {this.handleChangeAddress}/>
                        </Form.Field>
                        <br/>
                        <Button type='submit' floated='right' color='green'>Create</Button>
                        <Button floated='right' onClick={this.closeCreateForm} color='black'>Cancel</Button>
                        <br/>
                    </Form>

                </Modal.Content>
            </Modal>

        </div>
    )
}

}

【问题讨论】:

    标签: reactjs jsx semantic-ui-react


    【解决方案1】:
    function handleChangeName(event) {
        const value = event.target.value;
        this.setState((prevState)=>({ formData: { name: value, address: prevState.formData.address }}),
        ()=>{ console.log(this.state.formData)});
    }
    
    function handleChangeAddress(event) {
        const value = event.target.value;
        this.setState((prevState)=>({ formData: { name: prevState.formData.name, address: value}}),
        ()=>{ console.log(this.state.formData)});
    }
    
    1. 如果您在 setState() 或状态更新后接下来要做什么,则必须使用回调函数。
    2. 合并状态更新

    【讨论】:

      【解决方案2】:

      通过这些行,您将用一个字段的值替换整个状态:

      你的初始状态:

       state = {
             formData: {
                name: "",
                address: ""
             }
          }
      

      这行之后你的状态:

      this.setState({formData:{address:value}});

       state = {
             formData: {
                address: ""
             }
          }
      

      有了这一行: this.setState({formData:{name:value}});

      state = {
             formData: {
                name: ""
             }
          }
      

      正如 Greg b 的回答中提到的,您必须更改特定键的值并按原样复制其余部分。您还可以使用扩展运算符轻松复制其余未修改的字段。

      this.setState({...this.state.formData, address: value})
      

      只会更改地址并按原样复制其余状态。当状态中有多个字段时,这会很方便。

      【讨论】:

        【解决方案3】:

        这是你的状态

        formData:{
          name: '',
          address: ''
        }
        

        分别更改这两行

        this.setState({formData:{address:value}});
        
        this.setState({formData:{name:value}});
        

        this.setState({formData:{name: this.state.formData.name, address:value}});`
        
        this.setState({formData:{name:value, address: this.state.formData.address}});`
        

        【讨论】:

          【解决方案4】:

          您似乎没有正确访问render() 中的状态,我看到您在使用this.state.namethis.state.address 而不是this.state.formData.namethis.state.formData.address.

          此外,您可能不应该将表单数据存储在单个状态对象中,而是将其分解为每个输入的字段,例如

          this.state = {
            showCreateForm: false,
            name: "...",
            address: "..."
          }
          

          您不能只更新处于状态的对象的部分,您需要更新整个事物。当您执行this.setState({formData:{address:value}}); 或基本上将this.state.formData.name 设置为undefined 时,因为该对象现在将只是{ address: value }

          【讨论】:

          • 如果我这样做,我如何在 formData 中添加姓名和地址
          猜你喜欢
          • 2016-02-28
          • 1970-01-01
          • 2020-03-06
          • 2017-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-03-07
          • 2021-01-24
          相关资源
          最近更新 更多