当前位置: 代码迷 >> JavaScript >> React-成员函数在初始状态下(外部构造函数)调用时不是函数
  详细解决方案

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

热度:83   发布时间:2023-06-07 18:17:15.0

我有一个带有成员函数的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应该配置为接受此语法

    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" />
      )
   }
}
  相关解决方案