Vì vậy, tôi chỉ cần tải về mã nguồn từ một khuôn khổ Phản ứng, và tôi nhận được lỗi này trong Terminal:Tại sao thiết lập trạng thái của React Component bên ngoài constructor?
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 |
Câu hỏi của tôi là, tại sao người ta thiết lập một nhà nước Phản ứng phần của như thế này? Lợi ích nếu nó sẽ gây lỗi cho một số người? Ngoài ra, có một cài đặt trước Babel hoặc plugin tôi có thể nhận được để ngăn chặn lỗi này?
Đây là cách tôi thường được thiết lập trạng thái của một thành phần, và từ những gì tôi đã nhìn thấy, đây là truyền thống:
constructor() {
super();
this.state = {
state: initialState
};
}
Đối với hồ sơ, đây là toàn bộ tài liệu:
// 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 })}
/>
)
}
}