javascript – 为什么在构造函数之外设置React Component的状态?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 为什么在构造函数之外设置React Component的状态?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1794字,纯文字阅读大概需要3分钟。
内容图文
所以我刚刚从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 Component的状态?如果某些人的错误会有什么好处?另外,我可以使用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 Component的状态?全部内容,希望文章能够帮你解决javascript – 为什么在构造函数之外设置React Component的状态?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。