React getDerivedStateFromProps 无法访问此

Sag*_*che 5 javascript reactjs

我在最新的 react 16.5.2 中使用了 getDerivedStateFromProps 生命周期钩子。为什么我无法访问组件的 this 对象?有什么我做错了。

class EmailInput extends Component {
  state = { email: this.props.defaultEmail };

  handleChange = event => {
    this.setState({ email: event.target.value });
  };

  getDerivedStateFromProps() {
    this.doSomething();
  }

  doSomething = () => {
   //do something here
  }

  render() {
    return <input onChange={this.handleChange} value={this.state.email} />;
  }
}
Run Code Online (Sandbox Code Playgroud)

Bho*_*yar 4

您不能使用this访问非静态方法。您需要定义静态方法:

static getDerivedStateFromProps() {
    EmailInput.doSomething();
   // ^^ class name
   //OR,
   // this.doSomething(); // accessible, coz doSomething is now static method
}
static doSomething() {
   //do something here
}
Run Code Online (Sandbox Code Playgroud)

您可以在mdn 文档中了解有关静态方法的更多信息。


此外,我们在非静态方法中使用this.props,this.state分别访问 props 和 states。但由于getDerivedStateFromProps是一个静态方法,我们需要从它的参数访问:

static getDerivedStateFromProps(props, state) {
  // correct
  console.log(props, state)
 // incorrect
 // console.log(this.props, this.state)
 // `this` can be used only for static methods
 // that are inside the class
}
Run Code Online (Sandbox Code Playgroud)