繁体   English   中英

如何在ReactJS中的getDerivedStateFromProps内部调用方法?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM