简体   繁体   English

首选的ES6箭头函数语法格式

[英]Preferred ES6 arrow function syntax formatting

I have an onChange event handler that is shaping up like this: 我有一个像这样的onChange事件处理程序:

(e) => (value => this.setState(prevState => ({
        form: {
            ...prevState.form,
            email: value
        }
    })))(e.target.value)

I minified it down to that from this 我将其缩小为

(e) => {
    let value = e.target.value;
    this.setState((prevState) => ({
        form: {
            ...prevState.form,
            password: value
        }
    }))
}

Neither of these are very appealing. 这些都不是很吸引人。 I like the first one b/c it is 3 less lines of code but it also has a ton of parenthesis. 我喜欢第一个b / c,它少了3行代码,但是也有很多括号。 Is there another variation I might be missing that can clean this up further? 我可能还缺少其他可以进一步解决此问题的变体吗? The use of the spread operator adds an extra paren, could this be removed somehow? 使用点差运算符会增加一个额外的括号,可以以某种方式将其删除吗?

Thanks 谢谢

You could destructure out the value from the event and just do the setState as the only statement. 您可以从事件中setState出值,然后仅将setState做为唯一语句。

({ target: { value } }) => this.setState(prevState => ({
  form: {
    ...prevState.form,
    password: value
  }
}));

Personally I would use this: 我个人将使用此:

e => {
    let value = e.target.value;
    this.setState({
        form: {
            ...this.state.form,
            password: value
        }
    });
}

Just another idea for you :) 只是您的另一个主意:)

event => {
   const password = event.target.value;
   const form = { ...this.state.form, password };
   this.setState({ form });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM