Cannot store arrow function in let/var in React Component

孤街醉人 提交于 2019-12-13 21:34:45

问题


I have a component in react defined by extends React.Component. Inside it, along with the render method, is:

constructor(props, context) {
    super(props, context);

    this.state = {
        open: false,
    };
}

handleClose = () => { //this works
    this.setState({open: false});
};

handleOpen = () => { //this works
    this.setState({open: true});
};

let empty = () => {}; // does not work, error  Parsing error:      Unexpected token

I seem to get an unexpected token error if I prefix any of the arrow functions with let or const. Am I missing something here?

thanks


回答1:


Read babel documentation about classes. using let or const is not part of ES6 possible prefix for classes definition




回答2:


The ECMA 2015 spec seems to only allow methods and static methods in the body of a class definition.

So, in this case, assignment statements are not allowed, hence the Unexpected token error from babel.




回答3:


You're trying to use experimental ES7 features and likely only have ES6 enabled (also you cannot prefix let or const in a class). If you're using babel6 it should be simple to switch to the correct plugin. See this answer from basically the same question: How to use ES6 arrow in class methods?




回答4:


You seem to be making use of the class properties declartion proposal. The proposed syntax is:

class ClassWithoutInits {
  myProp;
}

class ClassWithInits {
  myProp = 42;
}

As you can see, no let or const or var. let empty = () => {}; doesn't work because it is not valid syntax, just like the error message tells you.



来源:https://stackoverflow.com/questions/37838756/cannot-store-arrow-function-in-let-var-in-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!