问题描述
我有一个带有成员函数的react类,该函数初始化状态:
class SomeComponent extends Component {
state = this.getInitialState(this.props)
getInitialState = (props) => {
// return some state based on props
}
}
我收到以下错误:
Unhandled Rejection (TypeError): _this.getInitialState is not a function
但是,如果我有一个显式声明的构造函数,则该组件可以正常工作
class SomeComponent extends Component {
constructor(props) {
super(props)
this.state = this.getInitialState(this.props)
}
getInitialState = (props) => {
// return some state based on props
}
}
为什么会这样?
编辑:我正在使用create-react-app,因此babel应该配置为接受此语法
1楼
class SomeComponent extends React.Component {
state = {}
static getDerivedStateFromProps(props, state) {
if (props.name !== state.newName) {
return {
newName: props.name+"value",
newSurname: props.surname+"value"
}
}
return null;
}
render () {
return (
<p>{this.state.newName} {this.state.newSurname}</p>
)
}
}
class ParentComponent extends React.Component {
render () {
return (
<SomeComponent name="Nick" surname="Pin" />
)
}
}