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
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:
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 ','
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.