我尝试调用此挂钩,但收到此错误
可能的未处理的 Promise 拒绝(id:6): 错误:无效的挂钩调用。钩子只能在函数组件的主体内部调用。
这是我的代码:
const handleEvento = async (dayy) => {
useEffect(()=>{
axios.get(`http://192.168.15.11:8085/api/readEventsByDate/${dayy}`)
.then(response =>{
//Ordenar os dados pelo id em ordem crescente
const sortData= response.data.sort((a,b) => a.id - b.id);
setData2(sortData);
console.log(data2)
})
.catch(error => {
console.log(JSON.stringify(error));
});
},[]);
}
onDayPress={day => {
handleEvento(day.dateString)
}}
我真的不知道我在这里缺少什么,如果有人可以帮助我,我会很高兴
React hooks 依赖于调用的顺序,因此如何使用它们有一些规则。文档的使用 Hooks 部分对此进行了描述。简而言之:你不能像以前那样使用钩子,因为它会使调用顺序不可预测。
在你的例子中,从逻辑角度来看,
useEffect()
的使用也不正确。你可以完全跳过它:
const handleEvento = async (dayy) => {
try {
const response = await axios.get(`http://192.168.15.11:8085/api/readEventsByDate/${dayy}`);
//Ordenar os dados pelo id em ordem crescente
const sortData = response.data.sort((a, b) => a.id - b.id);
setData2(sortData);
console.log(data2);
} catch (error) {
console.log(JSON.stringify(error));
}
};
请注意我如何使用
await
简化了您的代码。
还有一个注意事项 - 您的
console.log(data2)
将不会记录最新值,因为 setData2()
仅使用 queues 状态进行更新。它将在当前周期结束时得到有效改变。