我正在学习Udemy的反应课程,当我试图通过URL加载一个不存在的活动时,我遇到了一个奇怪的问题(这是因为我们的UI显然不会呈现无效的活动)。我确实验证了我的
useEffect
正确定义其依赖关系,以免造成通常会出现的无限循环:
useEffect(() => {
console.log("Params id: ", match.params.id);
loadActivity(match.params.id)
}, [loadActivity, match.params.id, history])
所讨论的组件具有以下签名
const ActivityDetails : React.FC<RouteComponentProps<DetailParams>>
当我查看控制台日志时,我可以看到这个使用效果一直被点击,但有趣的是,当它没有活动返回时,它的渲染返回(在同一组件内)也会被点击
if(!activity) {
console.log("not activity");
return <h2>Not Found</h2>
}
它的路径在其父容器中定义如下:
<Route key={location.key} path={['/createActivity', '/manage/:id']}
MobX动作的定义如下:
@action loadActivity = async (id: string) => {
let activity = this.getActivity(id);
console.log("activity is: ", activity);
if (activity !== undefined) {
this.activity = activity;
} else {
console.log("activity is undefined");
this.loadingInitial = true;
try {
activity = await agent.Activities.details(id);
console.log("after wait, acitivty is:", activity);
runInAction('getting activity',() => {
console.log("Now i am running the next run in action");
this.activity = activity;
this.loadingInitial = false;
})
} catch (error) {
runInAction('get activity error', () => {
this.loadingInitial = false;
})
console.log("Error Is: ", error);
}
}
}
我们获取活动的Agent如下:
const responseBody = (response: AxiosResponse ) => response.data;
const requests = {
get : (url: string) => axios.get(url).then(responseBody),
...
}
const Activities = {
details: (id: string) => requests.get(`/activities/detail/${id}`),
...
}
我到底做错了什么?
编辑:我不确定这是否是反应生命周期的一部分,但当我刷新该页面时,if(!activity)渲染似乎会被触发,但当然我们看不到它,因为它很快就会找到要渲染的活动。我对useEffect的理解是,它应该在安装组件之前先启动,定义那里的状态,然后继续生命周期?