英文:
React useEffect triggering on unMount when in Production
问题
我正在运行一个具有dotnet后端的React(Typescript)应用程序,本地一切正常,但一旦部署到Azure,我的useEffect钩子开始出现问题。例如,这个调用:
const getContacts = useCallback(
() => {
getAvailablePartnerContacts(id!.toString()).then(
partnerContacts => {
const _partnerContacts = partnerContacts.map(
pContact => ({
value: pContact.id|| "",
key: `${pContact.firstName} ${pContact.lastName}`
})
);
debugger;
const allContacts = [...contacts, ..._partnerContacts]
setContacts(allContacts)
setPreselectedId(props.selectedPartnerContactId || "None");
})
},[])
// 加载数据
useEffect(() => getContacts, [getContacts])
在本地主机上正常工作,但在部署版本中,只有在浏览器中点击后退按钮时,这个debugger
才会触发。我甚至无法在本地重现这个问题。有人有类似的经验吗?
英文:
I am running a React (Typescript) app with a dotnet backend and locally all works alright, but once I deploy it to azure my useEffect hooks start misbehaving. For example, this call:
const getContacts = useCallback(
() => {
getAvailablePartnerContacts(id!.toString()).then(
partnerContacts => {
const _partnerContacts = partnerContacts.map(
pContact => ({
value: pContact.id|| "",
key: `${pContact.firstName} ${pContact.lastName}`
})
);
debugger;
const allContacts = [...contacts, ..._partnerContacts]
setContacts(allContacts)
setPreselectedId(props.selectedPartnerContactId || "None");
})
},[])
//load data
useEffect(() => getContacts, [getContacts])
works fine under localhost, but in the deployed version this debugger
only triggers once I hit the back button in the browser. I cannot even reproduce this issue locally. Did anyone have similar experiences?
答案1
得分: 2
在你的情况下,你正在返回 getContacts
,这意味着你在组件卸载时调用它。考虑这样做:
useEffect(() => {
getContacts()
}, [])
英文:
In your case, you are returning the getContacts
wich means, your are calling it on component did unmount. Consider doing:
useEffect(() => {
getContacts()
}, [])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论