如何从React中的另一个静态方法调用静态方法?

Seb*_*736 4 javascript class jsx reactjs

我试图从React组件中的另一个静态方法调用静态方法:

class HelloWorld extends React.Component {

  static add(a, b){
    return a + b;
  }

  static getDerivedStateFromProps(props, state){
    const sum = this.add(2, 2);    
    return {
      sum
    }
  }

  render() {
    return <div>Hello World</div>
  }
}
Run Code Online (Sandbox Code Playgroud)

现场演示:https://codesandbox.io/s/rmxy909ovo

但是我得到了this未定义的错误,即使MDN说:

为了在同一个类的另一个静态方法中调用静态方法,可以使用this关键字.

为什么this在静态方法不定,如何调用该方法addgetDerivedStateFromProps在这个例子吗?

Est*_*ask 8

如果使用各自的上下文调用静态方法HelloWorld.getDerivedStateFromProps(),this则将引用类构造函数内部getDerivedStateFromProps,this === HelloWorld.

事实并非如此getDerivedStateFromProps.它是一个钩子,它作为类静态方法的目的是将提供的函数与特定组件相关联.它被渲染称为回调,没有this提供上下文.它的设计就是专门用于将它与类实例隔离开来,并防止在遗留生命周期钩子(componentWillReceiveProps等)中常见的可能的误用.

这里真正的问题是不add应该是HelloWorld方法,因为它不属于类.由于它无法访问组件实例,因此它只是一个使用该类作为命名空间的函数.在现代JS中使用类作为命名空间是反模式.相反,它可能是:

function add(a, b){
  return a + b;
}

class HelloWorld extends React.Component {
  static getDerivedStateFromProps(props, state){
    const sum = add(2, 2);    
    return {
      sum
    }
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)


小智 5

需要在类而不是实例上访问静态方法。所以试试这个:

HelloWorld.add(2,2);
Run Code Online (Sandbox Code Playgroud)