‘this’ 关键字在 React 中表现不同。

huangapple go评论61阅读模式
英文:

The 'this' keyword behaves differently in React

问题

纯JavaScript中,类的静态方法中的关键字this指的是类本身,但在React中,在静态方法getDerivedStateFromProps中,我注意到这个关键字并不指向类,当在控制台中进行日志记录时,它是未定义的。这种不同行为的原因是什么?

我尝试使用React生命周期方法。

英文:

In vanilla JavaScript, the keyword this in the static methods of a class refers to the class itself, but in React, in the static method getDerivedStateFromProps, I noticed that this word does not refer to the class, and when logging in the console, it is undefined. What is the reason for this different behavior?

I try use the React life cycle method.

答案1

得分: 1

在React中,this关键字用于引用组件类的当前实例。它允许您在类定义内部访问组件的props、state和方法。

getDerivedStateFromProps是一个在组件初始化之前调用的生命周期方法,因此您在其中无法访问this关键字。

如果您需要在内部访问props,请使用props参数,像这样:

static getDerivedStateFromProps(props, state) {
   console.log('getDerivedStateFromProps方法被调用');
   return { email: props.email };
}

https://legacy.reactjs.org/docs/react-component.html#static-getderivedstatefromprops

英文:

In React, the this keyword is used to refer to the current instance of a component class. It allows you to access the component's props, state, and methods within its class definition.

getDerivedStateFromProps is a lifecyle method that is invoked before the component is initiated and therefore you won't have access to the this keyword inside it.

If you need to access the props inside, use the props argument like this:

 static getDerivedStateFromProps(props, state) {
      console.log('getDerivedStateFromProps method is called');
      return { email: props.email };
   }

https://legacy.reactjs.org/docs/react-component.html#static-getderivedstatefromprops

huangapple
  • 本文由 发表于 2023年6月8日 15:55:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定