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

Why set a React Component's state outside of the constructor?

本文关键字:组件 React 状态 设置 外设 构造函数 为什么      更新时间:2023-09-26

所以我刚刚从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 | 

我的问题是,为什么人们这样设置一个React组件的状态?如果对某些人有误差,有什么好处呢?此外,是否有一个Babel预设或插件,我可以得到防止这个错误?

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

constructor() {
  super();
  this.state = {
    state: initialState
  };
}

为记录,这是整个文档:

// 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 })}
      />
    )
  }
}

第一个例子是使用类属性,这不是ES6规范的一部分,你可以使用它们与babel使用stage-2预置或babel-plugin-transform-class-properties插件模块。

的用法主要取决于个人偏好,并且在使用babel进行转译时将产生与第二个示例相同的结果。

https://babeljs.io/repl/?评估= true& lineWrap = false&预设= % 2 cstage-0&amp反应;实验= false&宽松= false&规范= false&代码= % 2 f % 2 f % 20代码% 20 % 20这里% 0 aclass % 20第一个% 20% 7 b % 0 3 d % % 20个州20% % 20% 20% 7 b % 0 a % 20% 20% 20% 20值% 3 a % 20真正% 0 a % 20% 20% 7 d % 0 a % 7 d % 3 b % 0 a % 0 aclass % 20秒7 b % 0 a % % 20% 20% 20构造函数% 20 ()% 7 b % 0 a % 20% 20% 20% 20% 20 this.state % 20% 3 d % 7 b % 0 a % 20% 20% 20% 20% 20% 20% 20值% 3 a % 20真正% 0 a % 20% 20% 20% 20% 7 d % 3 b % 0 a % 20% 20% 7 d % 0 a % 7 d % 3 b % 0