【问题标题】:How could I rewrite this without using arrow functions?如果不使用箭头函数,我怎么能重写它?
【发布时间】:2017-10-09 11:20:12
【问题描述】:

我不明白如何解开双箭头绑定。我的 linter 不喜欢这种 ES7+ 魔法。

    export default class Login extends Component {
     handleChange = (fieldName) => (evt) => {
        this.setState({
          [fieldName]: evt.target.value,
          errors: {...this.state.errors, [fieldName]: null}
        })
      }
  }

【问题讨论】:

  • 那么你应该修复你的 linter - 警告信息是什么?顺便说一句,箭头函数是 ES6,只有对象传播超出了 ES7。
  • 无论我的 linter 如何,我都想了解如何解决这个问题。我知道箭头是 ES6,但是初始化一个方法而不将它绑定到一个 react 类中绝对是 ES7+ 的魔法。警告是Unexpected token = (null)。我正在使用standardjs。
  • 这看起来也可能是类属性的主体。 ES6 的方式是将它放在你的构造函数中,或者让它成为一个方法并单独绑定它。
  • 没有迹象表明它是一种方法。我们应该如何猜测?
  • “在这种情况下,添加的类上下文无关紧要。” 完全不是,这正是问题所在。类字段是实验性的,箭头函数不是。

标签: ecmascript-6 arrow-functions ecmascript-next


【解决方案1】:

箭头函数没有问题,Unexpected token = 表示你的 linter 不喜欢 class fields。只需在构造函数中移动整个东西:

export default class Login extends Component {
  constructor() {
    super();
    this.handleChange = (fieldName) => (evt) => {
      this.setState({
        [fieldName]: evt.target.value,
        errors: {...this.state.errors, [fieldName]: null}
      });
    };
  }
}

【讨论】:

  • 这是有道理的。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2019-08-13
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 2017-08-28
  • 1970-01-01
相关资源
最近更新 更多