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

标签 javascript reactjs ecmascript-6

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

}

最佳答案

关于javascript - 为什么要在构造函数之外设置 React 组件的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184778/

相关文章:

javascript - 匹配特殊字符,包括方括号

javascript - 如何在 D3 中从 CSV 切换到 JSON? Github 类似图表

reactjs - 隐藏/显示 React-slick 箭头

javascript - 速记语法方法定义的标识符范围

javascript - 在第一个元素的处理结束之前,不要处理 forEach 循环中的下一个元素

javascript - ES6 Proxy 记录了无法解释的额外值

javascript - 正则表达式查找功能模块主体的起始行和列

javascript - 将变量发送到 RoR 中的 javascript 文件

javascript - 如何将单选按钮与输入文本字段绑定(bind)?

javascript - 获取键值对的嵌套对象数