React在生产环境中触发的useEffect卸载操作

huangapple go评论80阅读模式
英文:

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()
}, [])

huangapple
  • 本文由 发表于 2023年2月27日 16:01:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定