[英]How to call a method inside getDerivedStateFromProps in ReactJS?
我的React类中有一个方法,例如someMethod()
。 我也有一个getDerivedStateFromProps()
方法,我想在其中调用someMethod()
。 是的,例如,我需要在getDerivedStateFromProps
而不是componentDidUpdate()
执行此操作,因为我确实在someMethod()
更改了状态。
someMethod() {
this.setState({worked: true});
return 'worked';
}
static getDerivedStateFromProps(props, state) {
console.log(someMethod());
}
我希望显示worked
日志。
在getDerivedStateFromProps
您无权访问组件的实例。 所以,基本上,您不能。 但是您可以做的是返回一个对象以更新状态。
static getDerivedStateFromProps(props, state) {
return { worked: true }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.