所以我刚刚从 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 规范的类属性。您可以使用 stage-2
预设或 babel-plugin-transform-class-properties
插件模块将它们与 babel 一起使用。
使用主要是偏好问题,使用 babel 转译时会产生与第二个示例相同的结果。
关于javascript - 为什么要在构造函数之外设置 React 组件的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184778/