使用react(useeffect)获取jsonapi
你好,
这是我第一次使用 React。我想以 json 格式获取一些数据并将其列在我的页面中。下面的代码不起作用。
import React, { useState, useEffect } from "react";
import axios from "axios";
function DataFetching() {
const [users, setUsers] = useState({ hits: [] });
//const [query, setQuery] = useState("redux");
useEffect(async () => {
const fetchData = async () => {
const result = await axios("url");
setUsers(result.data);
};
}, []);
return (
<div>
<p>Hellooooo</p>
<ul>
{users.hits.map((user) => (
<li key={user.id}>{user.title}</li>
))}
</ul>
</div>
);
}
export default DataFetching;
回答
问题
useEffect钩子回调是 100% 同步的,它们根本不能是异步的(即声明的async)。这也隐式地返回一个 Promise 并与效果清理功能混淆。- 您的代码从不调用该
fetchData函数,因此没有真正更新。 - 您踩踏状态形状并将结果数组放置在根状态级别而不是
hits键下的对象中。
解决方案
async从效果回调中删除关键字。fetchData在效果回调体中调用。- 正确更新状态。
代码:
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios("url");
setUsers({ hits: result.data });
} catch(error) {
// handle any GET request or response handling errors
}
};
fetchData();
}, []);
- @AKX Not really sure what point you are trying to make, I didn't say the `useEffect` callback *couldn't* do asynchronous things, but that the callback itself can't be asynchronous. I did update to expressly call out the use of `async` keyword in the issues even though I felt it was already clear enough in context with the solution. Thanks for the input.