简体   繁体   English

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

[英]How to call a static method from another static method in React?

I am trying to call a static method from within another static method in a React component: 我试图从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>
  }
}

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

But I get the error that this is undefined, even though MDN says : 但是我得到的错误是this是未定义的,即使MDN说

In order to call a static method within another static method of the same class, you can use the this keyword. 为了在同一个类的另一个静态方法中调用静态方法,可以使用this关键字。

Why is this in a static method undefined and how to call the method add within getDerivedStateFromProps in this example? 为什么在静态方法中this是未定义的,如何在此示例中调用getDerivedStateFromProps中的方法add

If static method is called with respective context as HelloWorld.getDerivedStateFromProps() , this will refer to class constructor inside getDerivedStateFromProps , this === HelloWorld . 如果使用相应的上下文调用静态方法作为HelloWorld.getDerivedStateFromProps()this将引用getDerivedStateFromProps类构造getDerivedStateFromPropsthis === HelloWorld

This is not the case for getDerivedStateFromProps . getDerivedStateFromProps不是这种情况。 It is a hook, its purpose as class static method is to associate provided function with specific component. 它是一个钩子,它作为类静态方法的目的是将提供的函数与特定组件相关联。 It's called as a callback by the render without this context provided. 它在没有提供this上下文的情况下被渲染称为回调。 It was designed like that specifically to isolate it from class instance and prevent possible misuses that are common in legacy lifecycle hooks ( componentWillReceiveProps , etc). 它的设计就是专门用于将它与类实例隔离开来,并防止在遗留生命周期钩子( componentWillReceiveProps等)中常见的可能的误用。

The real problem here is that add shouldn't be HelloWorld method because it doesn't belong to the class. 这里真正的问题是add不应该是HelloWorld方法,因为它不属于该类。 Since it cannot access component instance, it's only a function that uses the class as a namespace. 由于它无法访问组件实例,因此它只是一个使用该类作为命名空间的函数。 Using classes as namespaces is antipattern in modern JS. 在现代JS中使用类作为命名空间是反模式。 Instead, it could be: 相反,它可能是:

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

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

You call static method from another see below code. 你从另一个调用静态方法看到下面的代码。

static getDerivedStateFromProps() {
   HelloWorld.add()
}

A static method needs to be accessed on the class not an instance. 需要在类而不是实例上访问静态方法。 So try this: 试试这个:

HelloWorld.add(2,2);

IMPORTANT UPDATE: This answer is incorrect, sorry. 重要更新:这个答案不正确,抱歉。 I should have double-checked that @ChrisG's comment was correct before posting it. 在发布之前,我应该仔细检查@ChrisG的评论是否正确。 @estus's answer is the correct answer. @ estus的答案是正确的答案。

If you paste your code into the Babel playground you can see that calling HelloWorld.getDerivedStateFromProps() directly indeed works as you intended, even compiling to ES5. 如果您将代码粘贴到Babel游乐场,您可以看到直接调用HelloWorld.getDerivedStateFromProps()确实可以按预期工作,甚至可以编译为ES5。


Original ( incorrect ) answer: 原始( 不正确 )答案:

(Note that this answer is only partially incorrect; using this to call one static method from another is indeed valid syntax in normal circumstances.) (注意,这个答案只是部分不正确;在正常情况下,使用this来调用另一个静态方法确实是有效的语法。)

While I personally don't find it as readable as using the class name ( HelloWorld ) explicitly, the code you originally posted is valid, and MDN is correct. 虽然我个人认为它不像显式使用类名( HelloWorld )那样可读,但您最初发布的代码是有效的,并且MDN是正确的。 As @ChrisG pointed out in his comment, the problem is that it doesn't work in code transpiled by Babel to ES5. 正如@ChrisG在他的评论中指出的那样,问题在于它在Babel向ES5转化的代码中不起作用。 If you change the target so it transpiles to ES6, it should work, although of course it won't work in browsers that don't support ES6. 如果您更改目标以使其转换为ES6,它应该可以工作,但当然它不适用于不支持ES6的浏览器。

Yes, You can't find this object in static method. 是的,您无法在静态方法中找到此对象。 But you can achive this in other hand. 但是你可以在另一方面实现这个目标。 You can declare a global variable and assign "this object" reference to that in constructor. 您可以声明一个全局变量,并将“this object”引用分配给构造函数中的那个。 You can check below code:- 您可以查看以下代码: -

import React, {Component} from 'react';
var _this;
class Toastr extends Component{
  constructor(props){
    super(props)
    this.state={
      visible: 'hide'
    }
    _this = this
  } 

  static handleShow = (isSuccess, message, code) => {
    _this.setState({visible: 'show', message: message})
    setTimeout( function(){
      _this.setState({visible: 'hide'})
    }, 3000)
  }

  render(){
    return(
      <div aria-live="polite" aria-atomic="true" className="toast-conatiner">
        <div className="toast-position">
           <div className={`toast ${this.state.visible}`} role="alert" aria-live="assertive" aria-atomic="true">
             <div class="toast-body">
                <span className={this.state.isSuccess ? 'text-success' : 'text-danger'}>{this.state.message}</span>
             </div>
           </div>
         </div>
       </div>
     );
   }
 }

 export default Toastr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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