简体   繁体   中英

Optimize the function in React. Having setState key as a props?

Having this function, which basically defines which form input to listen to. However as input is growing, so the function is growing also.

I was thinking about passing an id and compare it with the value of the key of the state so this state will change.

onChange = event => {
  if (event.target.id === "Name") {
    this.setState({
      name: event.target.value
    });
  } else if (event.target.id === "Position") {
    this.setState({
      position: event.target.value
    });
  } else if (event.target.id === "Text") {
    this.setState({
      text: event.target.value
    });
  }
};

So how to do it properly with the state?

I was thinking something like this. So the input form call the function with the id value and it finds a state with the same name|value.

onChange = (event, id) => {
  this.setState({
  { id value as a key?}: event.target.value
  })
}

However, do not understand how to write it correctly. Any help, please?

You can do this

onChange = event => {
    this.setState({
        [event.target.id]: event.target.value
    })
}

also change your element id to name , position and text

您更有可能应该使用useReducer

useReducer is usually preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one

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