为什么要在构造函数之外设置React组件的状态?
Why set a React Component's state outside of the constructor?
所以我刚刚从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&反应;实验= 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
- React重新渲染但未显示正确的组件
- React组件等待所需道具进行渲染
- 如何在react js中将值从一个组件发送到另一个组件
- React Native通过Navigator将用户输入数据传递到选项卡栏IOS中的组件
- React组件-设置页面标题
- 为react组件传递道具的最佳方式
- react组件中的绑定方法
- 如何在react js中移动第二个组件
- 如何在react路由器的组件中使用参数
- React+Redux性能优化与组件ShouldUpdate
- React-将jSON数据传递给子组件的子组件
- React js更改状态不会更新组件
- 加载服务器端渲染的React组件后执行脚本
- React ClickDrag子组件回调
- 如何在渲染函数中检查 react 中子组件的状态
- 以最封装的方式封装/封装ScalaJS react js组件(react stick)
- bind():您正在将一个组件方法绑定到该组件.React会自动为您执行此操作
- 如何将值从父组件传递到子组件(react)
- 将函数从HOC传递到组件(React, React native)
- 根据屏幕大小以不同的顺序呈现组件(React)