gpt4 book ai didi

javascript - 为什么 React 函数组件的 "this"未定义

转载 作者:行者123 更新时间:2023-12-04 14:39:27 27 4
gpt4 key购买 nike

我在 React 的箭头函数组件中测试了“this”变量。
每当我调用函数组件时,我预计“这个”值可能是全局变量。
因为据我所知,箭头函数中的“this”是在声明箭头函数时绑定(bind)的,“this”由词法作用域规则确定。
词法作用域的结尾是全局作用域,所以“this”可能是全局变量。
我想念什么?谢谢你。

export default (props) => {

console.log(this)

return (
<div>react this test</div>
)
}

最佳答案

函数组件可以使用两个箭头函数来编写 () => {}如上述问题所示,或作为正则函数表达式/声明,如 function Foo() {} .要了解为什么会发生上述行为,首先要了解 React 组件(通常)是在 ES6 modules 中编写的,这一点很重要。 .
为什么是 this undefined在箭头函数组件中?
模块的属性之一是 this在顶部的“模块范围”级别是 undefined .此行为不同于常规脚本:

<!-- A "module" is what react component code is usually written in -->
<script type="module">
console.log("Module code (react code) this:", this); // undefined
// ^
const App = () => { // example component |
this // --- taken from surrounding scope ---+
}
</script>

上面的例子显示了 this在模块范围内使用时默认为 undefined而不是像在标准脚本中那样使用全局对象(例如 window )。
在箭头函数内部, this 的值取自声明箭头函数的周围范围。在您的情况下,这是模块的顶层,所以 this取值 undefined .

为什么是 this undefined在常规功能组件内?
与上面的例子不同,函数表达式/声明如 function App() {}也可以用来定义我们的组件。在这种情况下,您会看到 this也是 undefined组件内。
要理解为什么会这样,需要记住的模块的另一个重要属性是它们会自动在 strict mode 中运行。 (强调我的):

Also, note that you might get different behavior from sections ofscript defined inside modules as opposed to in standard scripts. Thisis because modules use strict mode automatically


- MDN
在严格模式下,如果 this调用函数时未绑定(bind),函数的 this默认为 undefined ,与默认为全局对象的非严格/草率模式不同(例如浏览器中的 window):

In strict mode, however, if the value of this is not set when enteringan execution context, it remains as undefined, as shown in thefollowing example



function f2() {
'use strict'; // see strict mode
return this;
}

console.log(f2() === undefined); // true

- MDN
正则函数表达式/声明,如 function App() {}有自己的 this值并根据函数的调用方式设置。对于函数组件,React 以不设置 this 的方式调用它们。值(value)。在不以严格模式运行的标准脚本中,这将导致函数组件的 this但是,默认为全局对象(例如: window),因为我们在一个模块中,该行为不再适用。相反,由于模块自动在严格模式下运行,并且没有 this由 React 在调用组件时设置, this值默认为 undefined .

当您使用功能组件时,您不需要引用 this , 而是使用 Hook ,例如 useState() 来管理状态。

关于javascript - 为什么 React 函数组件的 "this"未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65974199/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com