简体   繁体   中英

How can I create a reusable function that will setState for a variable object property?

I have an onChange function to update the state on all of my form inputs. The state I'm trying to update here is nested in an array as an object, but I am unsure how I can make a reusable function that will update the specific object property depending on which form input is changed.

Here's my function:

onChangeHandler = (e, index) => {
  let currentStateObject = [...this.state.fundGroups]; //copying the current state

  // This works, but I don't want allocationName to be hardcoded. 
  // How can I pass in a variable that relates to the specific property 
  // based on which input field is changed?
  currentStateObject[index].allocationName = e.target.value; 
  this.setState({
    currentStateObject
  });
}

Here is what I have attempted but it does not work and breaks my code with an invalid token message:

currentStateObject[index].[e.target.name] = e.target.

I attempted this because in my input field, I added name="allocationName"

Does anyone know if I'm close to solving this? I'm very new to React. Thank you.

you almost got it. simply remove the . between [index] and [e.target.name] like:

currentStateObject[index][e.target.name] = e.target.value;

You can simply:

onChangeHandler(event) {
   this.setState({ [event.target.name]: event.target.value })
}

here is some example of state manipilation

state = {
    random: [],
    counter: 1
  }


  stateHandler = (e)=>{
    let oldrandom = [...this.state.random]
    oldrandom[e.target.name] = e.target.value;
    this.setState({random:oldrandom })
  }




manipulate state with a functional approach

 stateHandler = ()=>{
        this.setState((state,props)=>{
          counter: state.counter+props.increment
       })
      }

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