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

How to call a method inside getDerivedStateFromProps in ReactJS?

我的 React 中有一个方法 class 例如someMethod()。我还有一个 getDerivedStateFromProps() 方法,我想在其中调用 someMethod()。是的,我需要在 getDerivedStateFromProps 中执行此操作,而不是在 componentDidUpdate() 中执行此操作,因为我确实在 someMethod().

中更改了状态
someMethod() {
    this.setState({worked: true});
    return 'worked';
}

static getDerivedStateFromProps(props, state) {
    console.log(someMethod());
}

我希望显示 worked 的日志。

getDerivedStateFromProps 中,您无权访问组件的实例。所以,基本上,你不能。但是你可以做的是return一个更新状态的对象。

static getDerivedStateFromProps(props, state) {
    return { worked: true }
}