【问题标题】:React getDerivedStateFromProps not able to access thisReact getDerivedStateFromProps 无法访问此
【发布时间】:2023-03-26 22:57:01
【问题描述】:

我在最新的 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} />;
  }
}

【问题讨论】:

  • 确保在getDerivedStateFromProps前面加上static

标签: javascript reactjs


【解决方案1】:

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

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

您可以在mdn docs 了解更多关于静态方法的信息。


此外,我们使用this.propsthis.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
}

【讨论】:

  • 但是如果需要在某个promise函数之后调用setState呢?
  • 您不应该在此方法中设置承诺。这不是它的设计用途。
猜你喜欢
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多