Arrow function is considered unexpected token in React component using babel [closed]

為{幸葍}努か 提交于 2019-12-22 05:12:14

问题


I have this function in one of my react components.

export default class EventTags extends React.Component{
      showAll () => {
        this.setState({
          showAll: true,
          showBtn: false
        });
      }
}

When webpack watch hits it I get an unexpected token error on the arrow function. I have the transform-es2015-arrow-functions plugin enabled but it doesn't seem to change the outcome.

Any ideas on what i'm doing wrong here?


回答1:


You need an equals sign when using class property initializers.

export default class EventTags extends React.Component {
  showAll = () => {
    this.setState({
      showAll: true,
      showBtn: false
    });
  };
}
  • Ensure you have the transform-class-properties Babel transform enabled
  • Unlike class methods, class property initializers should be followed by semicolons

Babel's docs on arrow functions in ES6 React components shows longer examples.




回答2:


You need to assign the arrow function, below is the correct syntax for creating a named arrow function.

const showAll = () => {
  this.setState({
    showAll: true,
    showBtn: false
  });
}


来源:https://stackoverflow.com/questions/39495306/arrow-function-is-considered-unexpected-token-in-react-component-using-babel

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