简体   繁体   中英

javascript use in React setState

I'm studying a React book but see a simple like this, but I don't know why there is a ',' behind the [item]:value]

handleChange(item ,e) {
    const {value} = e.target;
    this.setState({[item]:value,});
}

render() {
    const {name, age} = this.state;
    return (
        <div className="FormA">
            name: <input value={name} onChange={this.handleChange.bind(this,'name')}/>
            age: <input value={age} onChange={this.handleChange.bind(this,'age')}/>
        </div>
    );
}

It is considered as best practice to have a ',' after every object property. You must have used ESLint: https://eslint.org/docs/rules/comma-style

It is just a matter of syntax and does not add anything to your code.

Its a best practice, because of the below reasons

  1. Its easier to track the commas. Eg. If you want a long list of object properties and you want to comment out some of them, then you need not worry about comas, as they are commented as well. Same goes for copy-paste.
  2. Its easier to see the diffs in version control.

The commas can be either at the end or at the front. [I usually use at front, personal choice.]

To Quote from ESList rules

The Comma Style rule enforces styles for comma-separated lists. There are two comma styles primarily used in JavaScript:

The standard style, in which commas are placed at the end of the current line

Comma First style, in which commas are placed at the start of the next line

One of the justifications for using Comma First style is that it can help track missing and trailing commas. These are problematic because missing commas in variable declarations can lead to the leakage of global variables and trailing commas can lead to errors in older versions of IE.

Refer:

https://eslint.org/docs/rules/comma-dangle ,

https://medium.com/@nikgraf/why-you-should-enforce-dangling-commas-for-multiline-statements-d034c98e36f8 ,

https://eslint.org/docs/rules/comma-style

This is because you can define a collection of named values to be set. If you're going to set only one you don't need to use it. In the same way the last element does't need it neither, for example:

this.setState({[item]:value}); //You don't necessary need the ',' here.

this.setState({
[item]:value,     //here you need to use ','
[item2]:value2,   //here you need to use ','
[item3]:value3}); //here you don't need to use ','

For more infor about objects check this link and this 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