簡體   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