React-成员函数在初始状态(外部构造函数)中调用时不是函数

时间:2019-02-12 15:25:11

标签: javascript reactjs

我有一个带有成员函数的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 个答案:

答案 0 :(得分:0)

Made example with lifecycle 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" />
      )
   }
}