我正在从 Facebook API 中提取一些数据,
const response = await axios.get('API ENDPOINT')
setData(response.data); // Assuming the data is in the response.data
console.log(response.data) //printing values
console.log('Data copied to state:', data); // Log the state after update
console.log(response.data)
这个在控制台中将数据正确记录为 JSON 对象
console.log('Data copied to state:', data)
给出一个空数组。
从 HTML 元素访问
{data?.length > 0 && (
<ul>
{data.map((item, index) => (
<li key={index}>
{/* Access item properties here */}
{item.email} - {item.last_name}
</li>
))}
如何将数据填充到数据对象中以在 HTML 元素中打印
React 中设置状态是异步的。这意味着
setData
函数不会立即改变提供的状态,而是创建一个挂起的状态转换。这就是为什么当您在设置数据后立即 console log
数据时看到空数组的原因。
您可能想实际检查渲染函数中的数据,或者在
useEffect
钩子之后检查数据(如果有的话)。
示例:
useEffect(() => {
const fetchData = async () => {
const response = await axios.get('API ENDPOINT')
setData(response.data);
}
fetchData();
}, []);
您将在组件上显示
data
,因此您无法使用 useRef
,因此使用 useEffect
,是我能看到的最佳方式。