为什么 React Function 组件的“this”未定义

LKB*_*LKB 3 javascript reactjs

我在 React 的 Arrow 函数组件中测试了“this”变量。

我期望“这个”值可能是全局变量每当我调用函数组件时。

因为据我所知,箭头函数中的'this'在声明箭头函数时被绑定并且'this'由词法作用域规则确定。

词法范围的结尾是全局范围,所以“this”可能是全局变量。

我想念什么?谢谢你。

export default (props) => {

  console.log(this)

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

Run Code Online (Sandbox Code Playgroud)

Nic*_*ons 6

React 组件(通常)是在ES6 模块中编写的,这些模块会在严格模式下自动运行(重点是我的):

另请注意,与在标准脚本中定义的脚本部分相比,您可能会从模块内部定义的脚本部分获得不同的行为。这是因为模块自动使用严格模式

- MDN

在严格模式下,如果this未绑定,则默认为undefined,不像在非严格/草率模式下默认为全局对象:

但是,在严格模式下,如果在进入执行上下文时未设置 this 的值,它将保持未定义状态,如下例所示

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

console.log(f2() === undefined); // true
Run Code Online (Sandbox Code Playgroud)

- MDN

当您使用功能组件时,您不应该需要引用this,而是使用钩子useState()来管理状态。

  • stackoverflow 上关于著名的“这是未定义”问题的最佳答案! (2认同)

Dej*_*dic 5

你不能在功能组件中使用它,也没有必要这样做。你可以直接访问 props,如果你需要 state,你可以使用 hooks。

import React, { useState } from 'react';

export default (props) => {
  const [state, setState] = useState(/* initial state here */);
  console.log(props, state)

  return (
    <div>react this test</div>
  )
}
Run Code Online (Sandbox Code Playgroud)

this在基于类的组件中的钩子之前使用:

class MyClass extends React.Component {
   render () {
     console.log(this.props, this.state);
   }
}
Run Code Online (Sandbox Code Playgroud)