简体   繁体   中英

Dynamically generating properties in a reactjs component's state

I have very large form, I would like to have a state that saves all of the user's input data, in different attributes named after the form.

So lets suppose I have a form with name, age and email. I want all of that to be saved in state called value. So once the form is filled I would have this.state.value[name] , this.state.value[age] and this.state.value[email] .

However this does not work, I get an error when I try to store the form's input data in that matter.

Here is the code for handleChange():

handleChange(e) {
     //this.setState({value[e.target.name]: e.target.value}); //does not work
     this.setState({[e.target.name]: e.target.value}); //works!
}

So how could I store the values in from the forms under a state attribute?

Thanks!

What if you do it like this:

const value = Object.assign({}, this.state.value)
value[e.target.name] = e.target.value
this.setState({ value })

value[e.target.name] is not a valid key. What you are attempting is to perform an update of the states value property, for which I would recommend something like immutability-helper .

In which case your update would look like:

this.setState({value: update(this.state.value, {[e.target.name]: {$set: e.target.value})})

Note that the use of Object.assign to create a copy as posted in another answer (+1) will achieve the same thing and is perfectly reasonable in this case. The immutability helper, however, is a useful tool to have for more complex updates.

First, I would like to point out that value is not defined in that method, which could be why you get the error (you never specified the exact error).

You would typically store the values as they are updated.

<input onChange={ e => this.setState({name: e.target.value}) />

Then, when the form is submitted, you would have access to all of the values in the state object.

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