Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

reactjs - React setState not working using event property

const [product, setProduct] = useState({
  productName: "",
  quantity: 0,
  basePrice: 0,
  sellPrice: 0,
})

const handleChange = (e) => {
  let fieldName = e.target.id;
  let fieldValue = e.target.value;
  setProduct({
    fieldName: fieldValue
  });
};

Code above doesnt seem to work. when i log fieldName however, it return productName.

I tried to explicitly use productName instead and its working

const handleChange = (e) => {
  let fieldName = e.target.id;
  let fieldValue = e.target.value;
  setProduct({
    productName: fieldValue
  });
}

Can anyone tell me whats going on under the hood why the initial approach is not working?

PS reason i want to use e.target.id is because there are multiple fields that needs updating Thank you

question from:https://stackoverflow.com/questions/65650026/react-setstate-not-working-using-event-property

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The setter on the useState doesn't work like the setState method on a React Class Component.

Setting just a particular field name would override the values of the other fields in the product Object and will set them to undefined.

You'll have to spread the existing product Object to get the values of the other fields and then only override the value of the field by using the [] notation to dynamically set the field name.

Something like this:

setProduct({ 
  ...product,
  [fieldName]: fieldValue 
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...