如何在React钩子中更新状态的单个属性?

时间:2019-11-07 18:36:15

标签: javascript reactjs react-hooks

我正在尝试更改状态挂钩,但出现此错误...我知道另一种更改方法,但它应该与传播语法一起使用,对吧?

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

1 个答案:

答案 0 :(得分:4)

第一件事是您需要useState

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

handleSldUrlChange function相比,您可以使用自定义回调来更新状态

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

演示:https://stackblitz.com/edit/react-mv8lsz