尝试在 useEffect 中 console.log 数据。不记录任何信息
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么,您需要从 API 中获取正确的返回有效负载的结构。它没有
accounts
属性。有效负载如下所示:
因此您可以在解构时重命名
data
属性。const { data: accountList } = wait res.json();
编辑:在解构时使用一些其他变量名称,混淆使用与状态相同的变量名称(
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:
So you can rename the
data
property while destructuring.const { data: accountList } = await res.json();
Edit: using some other variable name while destructuring, confusing to use the same variable name as the state (
accounts
).Working codesandbox
我要改变的一件事是使用 try/catch 围绕 async/await 语句。
如果您的await 语句失败,它将永远不会到达console.log 语句。
除非您有另一个组件处理这些错误,否则我会以这种方式使用它。
这就是我的建议:
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:
因为状态函数异步运行。因此,当您使用
setAccounts
时,它会以异步方式设置accounts
变量,因此有一种首选方法可以做到这一点,如下所示,我看到了
1.fetch 结果应该使用数据而不是帐户变量进行解构
2.setAccounts 函数以异步方式运行,因此它不会立即在下一行中打印结果
在此处检查 示例
since state function runs asyncronousely . therefore when you use
setAccounts
it setsaccounts
variable in async way , so there is a preferred way of doing this thing is as belowproblems 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
check here sample