React从Axios中获取REST API的数据,并使用RETEFFECT重新效应空数组加上数据
我正在尝试从REST API站点渲染数据,我可以在没有问题的情况下获取所有信息,但是首先用空数组来复制数据,这与Map()函数造成了冲突。
当我执行控制台徽标时,我可以看到重复。我需要的是仅获取具有数据和空数据的数组,或者我该如何选择数据数组,因为在我使用Map()函数时,我会读取错误,因为它读取空数组
usefetchdata.js
import { useEffect, useState} from 'react';
import http from '../../services/httpservices';
import config from '../../services/config.json';
const useFetchData = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const { data: response } = await http.get(config.apiEndpoint);
setData(response);
} catch (error) {
console.error(error)
}
setLoading(false);
};
fetchData();
}, []);
return {
data,
loading,
};
};
export default useFetchData;
customsite.jsx
import React, { useState } from 'react';
import Modal from './reusable/modal';
import useFetchData from './hooks/useFetchData';
const Customsite = ()=> {
const {
data,
loading,
} = useFetchData();
console.log(data);
return(
<div>
<p> we here </p>
</div>
)
}
export default Customsite
I am trying to render data from rest api site, I can get all info without issues, but is duplicating the data with an empty array first and this is creating a conflict with the map() function.
when I do a console logo I can see the duplication. what I need is to only get the array that has the data and the empty one or how can I select the array with data, since for somereason when i used the map() function I get error because its reading the empty array
useFetchData.js
import { useEffect, useState} from 'react';
import http from '../../services/httpservices';
import config from '../../services/config.json';
const useFetchData = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const { data: response } = await http.get(config.apiEndpoint);
setData(response);
} catch (error) {
console.error(error)
}
setLoading(false);
};
fetchData();
}, []);
return {
data,
loading,
};
};
export default useFetchData;
customsite.jsx
import React, { useState } from 'react';
import Modal from './reusable/modal';
import useFetchData from './hooks/useFetchData';
const Customsite = ()=> {
const {
data,
loading,
} = useFetchData();
console.log(data);
return(
<div>
<p> we here </p>
</div>
)
}
export default Customsite
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需要等到加载数据才能获得完整的数组,就必须将控制台日志调节到加载=== false
与要使用的地图函数相同。您需要添加此条件。要么测试data.length&gt; 0
you only need to wait until the data has loaded to get the full array, you must condition the console log to loading === false
the same goes with the map function you want to use. you need to add this condition. Either that or test if data.length > 0