尝试在 useEffect 中 console.log 数据。不记录任何信息

发布于 2025-01-11 03:41:29 字数 492 浏览 1 评论 0原文

function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { accounts } = await res.json();

      setAccounts(accounts);
      console.log(accounts);
    }

    fetchAccounts();
  }, []);
 
}

我试图理解为什么 console.log 在这个示例中没有显示任何内容,以及 console.log 从 api 获取的数据的正确方法是什么。

function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { accounts } = await res.json();

      setAccounts(accounts);
      console.log(accounts);
    }

    fetchAccounts();
  }, []);
 
}

I'm trying to understand why console.log shows nothing in this example and what is the correct way to console.log the data that is being fetched from the api.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

维持三分热 2025-01-18 03:41:29

那么,您需要从 API 中获取正确的返回有效负载的结构。它没有 accounts 属性。

有效负载如下所示:

{
  "success":true,
  "data":[{"account":"joejerde","assets":"11933"},{"account":"protonpunks","assets":"9072"}],
  "queryTime": 1646267075822
}

因此您可以在解构时重命名 data 属性。 const { data: accountList } = wait res.json();

function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { data: accountList } = await res.json();

      setAccounts(accountList);

      // logging both the state and the fetched value
      console.log(accounts, accountList);
      // accounts (state) will be undefined
      // if the fetch was successful, accountList will be an array of accounts (as per the API payload)
    }

    fetchAccounts()
  
  }, [])

  return <div>
    {JSON.stringify(accounts)}
  </div>
}

编辑:在解构时使用一些其他变量名称,混淆使用与状态相同的变量名称(accounts )。

工作 codesandbox

Well, you need to get the structure of the returned payload from the API correct. It does not have an accounts property.

The payload looks like this:

{
  "success":true,
  "data":[{"account":"joejerde","assets":"11933"},{"account":"protonpunks","assets":"9072"}],
  "queryTime": 1646267075822
}

So you can rename the data property while destructuring. const { data: accountList } = await res.json();

function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { data: accountList } = await res.json();

      setAccounts(accountList);

      // logging both the state and the fetched value
      console.log(accounts, accountList);
      // accounts (state) will be undefined
      // if the fetch was successful, accountList will be an array of accounts (as per the API payload)
    }

    fetchAccounts()
  
  }, [])

  return <div>
    {JSON.stringify(accounts)}
  </div>
}

Edit: using some other variable name while destructuring, confusing to use the same variable name as the state (accounts).

Working codesandbox

哑剧 2025-01-18 03:41:29

我要改变的一件事是使用 try/catch 围绕 async/await 语句。
如果您的await 语句失败,它将永远不会到达console.log 语句。
除非您有另一个组件处理这些错误,否则我会以这种方式使用它。

这就是我的建议:

function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    try {
     async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { accounts } = await res.json();

      setAccounts(accounts);
      console.log(accounts);
     }
    } catch (err) {
      console.log(err)
      // do something like throw your error
    }

    fetchAccounts();
  }, []);
 
}

One thing I would change is working with try/catch surrounding async/await statements.
If your await statement fails it will never reach the console.log statement.
Unless you have another component handling those errors, I would use it in that way.

That is my suggestion:

function UserAccounts() {
  const [accounts, setAccounts] = useState();

  useEffect(() => {
    try {
     async function fetchAccounts() {
      const res = await fetch(
        'https://proton.api.atomicassets.io/atomicassets/v1/accounts'
      );
      const { accounts } = await res.json();

      setAccounts(accounts);
      console.log(accounts);
     }
    } catch (err) {
      console.log(err)
      // do something like throw your error
    }

    fetchAccounts();
  }, []);
 
}
—━☆沉默づ 2025-01-18 03:41:29

因为状态函数异步运行。因此,当您使用 setAccounts 时,它会以异步方式设置 accounts 变量,因此有一种首选方法可以做到这一点,如下所示,

我看到了

1.fetch 结果应该使用数据而不是帐户变量进行解构

2.setAccounts 函数以异步方式运行,因此它不会立即在下一行中打印结果

import { useEffect, useState } from "react";

export default function App() {
  const [accounts, setAccounts] = useState();

  async function fetchAccounts() {
    const res = await fetch(
      "https://proton.api.atomicassets.io/atomicassets/v1/accounts"
    );
    const { data } = await res.json();
    setAccounts(data);
  }

  // on component mount / onload
  useState(() => {
    fetchAccounts();
  }, []);

  // on accounts state change
  useEffect(() => {
    console.log(accounts);
  }, [accounts]);

  return <div className="blankElement">hello world</div>;
}

在此处检查 示例

since state function runs asyncronousely . therefore when you use setAccounts it sets accounts variable in async way , so there is a preferred way of doing this thing is as below

problems i seen

1.fetch result should destructured with data instead of accounts variable

2.setAccounts function is running async way so it will not print result immedietly in next line

import { useEffect, useState } from "react";

export default function App() {
  const [accounts, setAccounts] = useState();

  async function fetchAccounts() {
    const res = await fetch(
      "https://proton.api.atomicassets.io/atomicassets/v1/accounts"
    );
    const { data } = await res.json();
    setAccounts(data);
  }

  // on component mount / onload
  useState(() => {
    fetchAccounts();
  }, []);

  // on accounts state change
  useEffect(() => {
    console.log(accounts);
  }, [accounts]);

  return <div className="blankElement">hello world</div>;
}

check here sample

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文