我在使用钩子获取数据时出现以下错误。我有两个功能组件
function TopTen() {
const [topTen, setTopten] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
console.log("useEffect TopTen has been called!");
const fetchdata = async () => {
const response = await api.topTen(); // this calls axios(url)
setLoading(false);
setTopten(response.data);
setError(response.error);
};
fetchdata ();
}, []);
return (
{topTen.length > 0 &&
<Table
tableData={topTen.map((item, idx) => {
return ([
item.name
]);
})}
/>
}
)
}
function Declaraciones() {
// ... here I'm using other effects also for fetching data
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const response = await api.fetch();
//...
};
fetchData ();
}, []);
return (
<div>
<p>{data}</p>
<TopTen />
</div>
)
}
出于某种原因,有时TopTen组件工作良好,有时则不然。这就像是随机的。我看到的是,api调用返回像"缓存"这样的假数据,所以当试图映射结果时失败了:
**TypeError: Cannot read property 'name' of undefined**
也许我错过了useeffect钩子的概念。
有人知道我该怎么解决吗?
感谢
您必须使用await-response.json((将响应转换为json;然后使用setState。
useEffect(() => {
console.log("useEffect TopTen has been called!");
const fetchdata = async () => {
const response = await api.topTen(); // this calls axios(url)
const responseData = await response.json();
setLoading(false);
setTopten(responseData.data);
setError(responseData.error);
};
fetchdata ();
}, []);
try:
setTopten(response.data.filter(function(val){ return val!==undefined; }))