admin管理员组

文章数量:1319487

I am looping through fields, validating them, and want to set a validation state inside this loop if they fail the validation:

Object.keys(validatedFields).map(field => {
  if (validateExists(field.value) === false) {
    this.setState({ validatedFields[field].message: 'error' })
    formIsValid = false
  }
})

However, I get a syntax error:

Unexpected token:
this.setState({ validatedFields[field].message: 'error' })
                               ^

How can I use this sort of "dynamic" key?

I am looping through fields, validating them, and want to set a validation state inside this loop if they fail the validation:

Object.keys(validatedFields).map(field => {
  if (validateExists(field.value) === false) {
    this.setState({ validatedFields[field].message: 'error' })
    formIsValid = false
  }
})

However, I get a syntax error:

Unexpected token:
this.setState({ validatedFields[field].message: 'error' })
                               ^

How can I use this sort of "dynamic" key?

Share Improve this question asked Aug 11, 2016 at 14:57 j_dj_d 3,08210 gold badges55 silver badges96 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

For dynamic state key, you can use Computed Property

Example:

const a = 'apple'

this.setState({
  [a]: 10 // is same as {apple: 10}
})

In your scenario, I'm not sure how do you want your state structure to look like, but if you want the state key to be validatedFields[field], then you can do:

this.setState({
  [validatedFields[field]]: 'error'
})

If you want message to be nested under it, then you can write:

this.setState({
  [validatedFields[field]]: {
    message: 'error'
  }
})

Replace:

this.setState({ this.state.validatedFields[field].message: 'error' })

with

var state = {};
state[this.state.validatedFields[field].message] = 'error';
this.setState(state);

Hope this works: this.setState({[this.state.validatedFields[field].message]: 'error'}); It can be done in one line, Square bracket evaluate what is inside. refer ES6 on Computed property names: https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

本文标签: javascriptHow to use square brackets in React setStateStack Overflow