我正在向数据库发出 get 请求以获取一些数据。它总是首先返回默认状态(一个空对象)。然后它按预期获取数据。我该如何解决?
export default function useEventIdSearch(id) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
const [event, setEvent] = useState({})
useEffect(() => {
setLoading(true)
setError(false)
let cancel
axios({
method: 'GET',
url: `https://website.com/${id}?`,
params: { api_key: 'dsfa' },
cancelToken: new axios.CancelToken(c => cancel = c)
}).then(res => {
setEvent(res.data)
setLoading(false)
})
.catch(e => {
if (axios.isCancel(e)) return
setError(true)
})
return () => cancel()
}, [id])
return { loading, error, event}
}
附言我是一个新手,所以我为我的问题道歉,因为我想这是我的一个错误并且与异步 JS 相关。