[英]ReactJS - Unexpected token '.' error
I am starting with my react project on VS2013 working together with ASP.NET MVC. 我从与ASP.NET MVC一起在VS2013上进行我的React项目开始。 I have configured webpack and configuration seemed working well until I tried to implement the following class.
我已经配置了webpack,在尝试实现以下类之前,配置似乎运行良好。
class Hello extends React.Component {
this.state = { visible: true }
render() {
/** Method definition **/
...
}
I am getting an error Unexpected Token at '.' 我在“。”处收到错误的意外令牌。 at 'this.state'.
在“ this.state”。 I have already check es2015 is set as babel preset.
我已经检查过将es2015设置为babel预设。 If I remove state and toggleVisibility assignments, webpack bundles OK.
如果我删除状态和toggleVisibility分配,则webpack捆绑确定。
Any idea what else can I try? 知道我还能尝试什么吗?
It's a class so the correct syntax should be 这是一个类,因此正确的语法应该是
class Hello extends React.Component {
state = { visible: true }
render() {
/** Method definition **/
...
}
Also, the recommended way of defining initial state should be 此外,建议的定义初始状态的方法应为
class Hello extends React.Component {
constructor(props) {
super(props)
this.state = { visible: true }
}
render() {
/** Method definition **/
...
}
You should define this.state
in a constructor like 您应该在类似的构造函数中定义
this.state
constructor(props) {
super(props);
this.state = {
visible: true
};
}
Hence, your code should be 因此,您的代码应为
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true
};
}
render() {}
}
From React docs : 从React docs :
The constructor is the right place to initialize state.
构造函数是初始化状态的正确位置。 If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.
如果您不初始化状态并且不绑定方法,则无需为React组件实现构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.