Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...