了解 React useEffect 函数

Understanding React useEffect functions

我正在尝试了解如何在 React 中调用 Flask API。目前,我在 App.js 文件中的 App() 函数中定义了这个函数:

useEffect(() => {
    fetch('/').then(response =>
      response.json().then(data => {
        console.log(data)
      })
      )
  }, [])

我对 JavaScript 没有太多经验,我知道 React 的 JSX 可能会令人困惑,所以我希望有人能澄清我对这个功能的理解。

我认为这意味着什么:

  1. 在启动时(用[]表示),调用这个没有输入的JS函数(用{}括号表示),如第一组空括号()
  2. 从 flask 应用程序中,使用指示的路由调用端点
  3. 采用此响应(我们有 named 响应?),运行 json() 方法将正文读取为 json
  4. 结果(我们有 named 数据?)然后记录在控制台中。这里的花括号再次表示这是 JS(X) 代码

这是正确的吗?非常感谢任何反馈!

On startup (indicated by []), call this JS function (as indicated by the {} brackets) that has no input as indicated by the first set of empty parentheses ()

非常正确。但重要的是要知道为什么 [] 表示“启动时”

useEffect 有两个参数。 运行 的函数和要监视的依赖项列表。在任何依赖项发生更改后,该函数将立即重新 运行。 dependencies 是一个空数组这一事实意味着它只会 运行 一次,紧接在第一次渲染之后,因为 none 的依赖项可能会改变。

From the flask application, call the endpoint with the route indicated.

不确定 flask 是什么,但这会向域上的 / 路径发出请求,该 React 应用程序正在其上提供服务。

Take this response (which we have named response?), and run the json() method to read the body as json

fetch returns 一个最终会实现的承诺。您在该函数上调用 then 以提供一个在该承诺解决时调用的函数。该函数接受一个参数,该参数是已解决承诺的值。您可以随意命名它,就像任何 javascript 函数参数一样。

The result (which we have named data?) is then logged in the console. The curly brackets here again denoting that this is JS(X) code

这里response.json returns 另一个等待响应数据被解析为JSON的承诺。您调用 then 处理该完成的新承诺。

我不确定大括号是什么意思,但这只是一个 javascript 数据结构。此发布的代码中唯一的 {} 声明了函数体。


您的代码中没有 JSX。只有普通的 javascript 调用 React 提供的函数。

JSX以尖括号为特征,例如:

<div>{someJavascriptvariableHere}</div>

会是 JSX。