英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论