简体   繁体   中英

React State with object

I am trying to update my state from my react dynamically, this is my current state.

this.state = {
      title: "",
      image: "",
      imageFile: "",
      formTitle: "",
      formMessage: "",
      formImage: "",
      Item: {
        name: "Name",
        price: "",
        quantity: "",
        discount: "",
        shipping: "",
        image: "",
        formType: ""
      }
    }

How do I update in my Textbox dynamically instead of one by one?

 setItemName = (name) => {
    this.setState({
      Item: {
        ...this.state.Item,
        name
      }
    });
  };

this is my attempt at solving this

and this is my Textbox using material UI

<TextField
                      className="my-24"
                      label="Item Name"
                      autoFocus
                      id="itemName"
                      name="itemName"
                      width={1}
                      value={this.state.Item.name}
                      onChange={this.setItemName}
                      variant="outlined"
                    />

Thanks!!

As I understand from your doubt, you want to change the fields in state dynamically instead of writing the functions one by one....

setItemName = (changedValue, type) => {
  this.setState({
    Item: {
      ...this.state.Item,
      [type]: changedValue
    }
  });
};

And your TextField going to be...

<TextField
  className="my-24"
  label="Item Name"
  autoFocus
  id="itemName"
  name="itemName"
  width={1}
  value={this.state.Item.name}
  onChange={(changedValue) => this.setItemName(changedValue, 'name')}
  variant="outlined"
/>

You just need to pass the state field name in the setItemName argument. As for 'price' you need to write setItemName(changedValue, 'price')

And nevermind,

I solve this,

This is my code for reference:

setItemValue = (field,value) => {
    console.log(field,value)
    this.setState(prevState => ({
      Item: {                   // object that we want to update
          ...prevState.Item,    // keep all other key-value pairs
          [field] : value       // update the value of specific key
      }
  }))

You can also try the following code

handleChange = e => {
  this.setState({
     Item: {
       ...this.state.Item,
      [e.target.name]: e.target.value
     }
});

Use name attribute as your state key:

<TextField
    rowsMax={4}
    placeholder="Enter name"
    value={name}
    name="name"
    onChange={this.handleChange}
  />
setItem = (key, value) => {
  this.setState({
    Item: {
      ...this.state.Item,
      [key]: value
    }
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM