[英]React - member function is not a function when called in initial state (outside constructor)
我有一個帶有成員函數的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應該配置為接受此語法
使用生命周期的示例getDerivedStaetFromProps
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" />
)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.