【发布时间】:2020-04-02 05:50:24
【问题描述】:
使用挂钩获取数据时出现以下错误。 我有两个功能组件
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 挂钩的概念。
有谁知道我该如何解决这个问题?
谢谢
【问题讨论】:
-
您确定您的后端每次都发送一致的架构作为响应吗?
-
@UtsavPatel 是的,我正在用邮递员测试我的后端 API,它没问题。奇怪的是,有时当从前端发送请求时,它会返回好的结果和其他一些不好的结果。我不知道为什么。我正在调试 axios 请求,显然没问题
-
当返回错误数据时,它属于我之前/之后正在执行的另一个获取请求,例如请求 1 => 数据 1 请求 2 => 数据 2 --- 这里我的后端返回数据 1请求 3 => 数据 3
标签: reactjs axios react-hooks