简体   繁体   中英

Changing input of controlled component changes property value to undefined

I have an array of default values in a useState. Upon an onChange event via a select, the properties in the array are changed to undefined. I've been reading up on controlled components and I think I've missed something silly.

Here is a codesandbox.

const [config, setConfig] = useState([{
  carType: "Sedan",
  carColor: "Red"
}]);

// onChange
const setCarType = (e) => {
  setConfig({ ...config[0], carType: e.target.value });
};

const { carType, carColor } = config[0];

I thought that I could use the spread operator here in order to copy the two properties of config[0] into two separate constants. I originally had the config in an object but was thrown an error "Objects are not valid as a react child".

  const setCarType = (e) => {
    setConfig([{ ...config[0], carType: e.target.value }]);
  };

  const setCarColor = (e) => {
    setConfig([{ ...config[0], carColor: e.target.value }]);
  };

When you were setting config, you were setting a new object as config but it was initialized as an array of objects. So config[0] was undefined cause config was no more an array. Try the above code, it will solve the issue.

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