簡體   English   中英

為什么 React Function 組件的“this”未定義

[英]Why React Function Component's "this" is undefined

我在 React 的 Arrow function 組件中測試了“this”變量。

我預計“這個”值可能是全局變量每當我調用 function 組件時。

因為據我所知,箭頭 function 中的“this”在聲明箭頭 Function 並且“this”由詞法 Z5D113F2038D289F391614C39043629E8 規則確定時被綁定。

詞法 Scope 的結尾是全局 Scope,所以“this”可能是全局變量。

我想念什么? 謝謝你。

export default (props) => {

  console.log(this)

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

Function 組件可以使用兩個箭頭函數() => {}來編寫,如上述問題所示,或者作為常規 function 表達式/聲明,例如function Foo() {} 要理解為什么會發生上述行為,首先要了解 React 組件(通常)是在ES6 模塊中編寫的,這一點很重要。

為什么在箭頭 function 組件this undefined

模塊的屬性之一是頂層“模塊范圍”級別的thisundefined 此行為不同於常規腳本:

 <.-- 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在模塊 scope 內部使用時如何默認為undefined而不是全局 object (例如window ),就像在標准腳本中一樣。

在箭頭函數內部, this的值取自在其中聲明了箭頭 function 的周圍 scope 。在您的情況下,這是模塊的頂層,因此this采用undefined的值。


為什么在常規 function 組件this undefined

與上面的示例不同,function 表達式/聲明,例如function App() {}也可以用於定義我們的組件。 在這種情況下,您會看到this在組件中也是undefined的。

要理解為什么會這樣,要記住的模塊的另一個重要屬性是它們會自動以嚴格模式運行(強調我的):

另外,請注意,您可能會從模塊內定義的腳本部分獲得不同的行為,而不是在標准腳本中。 這是因為模塊自動使用嚴格模式

-MDN

在嚴格模式下,如果在調用 function 時this未綁定,則函數的this默認為undefined ,不像在非嚴格/草率模式下默認為全局 object (例如瀏覽器中的window中的 Z05B8C34CBD96FFBF2DE4C1)

但是,在嚴格模式下,如果進入執行上下文時未設置 this 的值,則它保持為未定義,如下例所示

 function f2() { 'use strict'; // see strict mode return this; } console.log(f2() === undefined); // true

-MDN

常規 function 表達式/聲明,如function App() {}有自己的this值,並根據 function 的調用方式設置。 對於 function 組件,React 以不設置this值的方式調用它們。 在未在嚴格模式下運行的標准腳本中,這將導致 function 組件的this默認為全局 object (例如: window ),但是,該行為不再適用於模塊中。 相反,由於模塊自動在嚴格模式下運行,並且 React 在調用組件時沒有設置this ,所以this值默認為undefined


當你使用功能組件時,你應該不需要參考this ,而是使用useState()類的鈎子來管理 state。

您不能在功能組件中使用它,也沒有必要。 您可以直接訪問道具,如果您需要 state 可以使用鈎子。

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>
  )
}

this是在基於類的組件中的鈎子之前使用的:

class MyClass extends React.Component {
   render () {
     console.log(this.props, this.state);
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM