我对整个反应世界来说是一个全新的人,但是我正在尝试开发一个带有集成日历的SPA。我正在使用react-router进行路由,对日历使用react-big-calendar,对API调用使用axios和webpack。每当我加载日历组件时,它都会多次挂载和卸载,我认为这会使我的API调用从不实际获取任何数据。我只是不知道是什么原因造成的。
代码:
useEffect(() => {
console.log("mounting Calendar")
let source = Axios.CancelToken.source()
if(!initialized) {
console.log("getting Data")
getCalendarEvents(source)
}
return () => {
console.log("unmounting Calendar")
source.cancel();
}
})
const getCalendarEvents = async source => {
setInitialized(true)
setLoading(true)
try {
const response = await getCalendar({cancelToken: source.token})
const evts = response.data.map(item => {
return {
...item,
}
})
calendarStore.setCalendarEvents(evts)
} catch (error) {
if(Axios.isCancel(error)){
console.log("caught cancel")
}else{
console.log(Object.keys(error), error.message)
}
}
setLoading(false)
}
这是我渲染组件时的结果:Console log
如果您需要更多代码来评估问题,我将发布它。感谢您为解决我的问题提供的各种意见。
谢谢
这是由于useEffect。如果您希望它仅在安装时运行一次,则需要传递一个空数组作为依赖项,如:
useEffect(() => {
console.log("mounting Calendar")
let source = Axios.CancelToken.source()
if(!initialized) {
console.log("getting Data")
getCalendarEvents(source)
}
return () => {
console.log("unmounting Calendar")
source.cancel();
}
},[])
这意味着它将只运行一次。如果存在某种状态或道具,那么您可以随时监视数组中的状态。这意味着useEffect将监视其依赖项数组中传递的所有内容的更改,并在检测到更改时重新运行。如果为空,它将在安装时运行。