简体   繁体   中英

How to update a single property of the state in a react hook?

I'm trying to change a state hook and I got this error... I know another way to change but it should work with the spread syntax, right?

export default function App() {
  const [state, setState] = {
    sld_url: "",
    geojson_url: "",
  }

  const handleSldUrlChange = event => {
    setState({...state, sld_url: event.target.value})
  }

  return (
    <TextField
     label="SLD URL"
     value={state.sld_url}
     className={classes.textField}
     onChange={handleSldUrlChange}
     margin="normal"
     variant="outlined"
    />
  );
}

First thing is you need to useState :

const [state, setState] = useState({
    sld_url: "",
    geojson_url: "",
  })

Than inside handleSldUrlChange function you can use a custom callback for updating state

const handleSldUrlChange = event => {
    setState(prev => {...prev, sld_url: event.target.value})
   //or
   //setState({...state,sld_url: event.target.value})
  }

Demo: https://stackblitz.com/edit/react-mv8lsz

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