为什么在构造函数之外设置React Component的状态?

Mat*_*hew 12 javascript ecmascript-6 reactjs

所以我刚刚从React框架下载了源代码,我在终端中收到了这个错误:

  ERROR in ./src/components/TextEditor.js
  Module build failed: SyntaxError: Unexpected token (24:8)

  22 | 
  23 |   // Set the initial state when the app is first constructed.
> 24 |   state = {
     |         ^
  25 |     state: initialState
  26 |   }
  27 | 
Run Code Online (Sandbox Code Playgroud)

我的问题是,为什么人们会像这样设置React Component的状态?如果某些人的错误会有什么好处?另外,我可以使用Babel预设或插件来防止此错误吗?

这就是我通常设置组件状态的方式,从我看到的情况来看,这是常规的:

constructor() {
  super();
  this.state = {
    state: initialState
  };
}
Run Code Online (Sandbox Code Playgroud)

为了记录,这是整个文件:

// Import React!
import React from 'react'
import {Editor, Raw} from 'slate'

const initialState = Raw.deserialize({
  nodes: [
    {
      kind: 'block',
      type: 'paragraph',
      nodes: [
        {
          kind: 'text',
          text: 'A line of text in a paragraph.'
        }
      ]
    }
  ]
}, { terse: true })

// Define our app...
export default class TextEditor extends React.Component {

  // Set the initial state when the app is first constructed.
  state = {
    state: initialState
  }

  // On change, update the app's React state with the new editor state.
  render() {
    return (
      <Editor
        state={this.state.state}
        onChange={state => this.setState({ state })}
      />
    )
  }

}
Run Code Online (Sandbox Code Playgroud)