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