我在最新的 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.props
、this.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/