javascript - react getDerivedStateFromProps 无法访问这个

标签 javascript reactjs

我在最新的 React 16.5.2 中使用 getDerivedStateFromProps 生命周期钩子(Hook)。为什么我无法访问组件的 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} />;
  }
}

最佳答案

您不能使用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和state。但是自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
}

关于javascript - react getDerivedStateFromProps 无法访问这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52630690/

相关文章:

javascript - 为 document.cookie 定义 getter

reactjs - Material UI 数据网格性能

javascript - 如何在函数中访问 State 中的键值?

javascript - 即使在服务器和客户端上设置 header 后,请求的资源上仍存在错误 "No ' Access-Control-Allow-Origin' header

javascript - 每 5 小时执行一次函数,在 Firefox OS 中使用 Alarm API

javascript - react 羽毛笔 onBlur 不工作

javascript - 全日历刷新/重新定义所有事件

javascript - 可编辑网格 ExtJS,如何在网格上编辑行后更新数据库中的行

javascript - Facebook 的 react.js——对象不是函数

javascript - react .js : Is it possible to namespace child components while still using JSX to refer to them?