React Context无限期调用函数



我有这个配置文件,我从我的上下文中加载,但它是调用函数一遍又一遍。如何使只被调用一次或仅当需要时.例如,我有2情态动词,其中一个被称为,如果没有配置文件存在,一个配置文件存在。但是当第二个模态被调用时,我看到profile一遍又一遍地被调用,但我希望它只被调用onLoad和当改变profile发生(更新,删除profile)。

interface ProfileContext {
openProfile: boolean
setOpenProfile: React.Dispatch<React.SetStateAction<boolean>>
profile: Profil | undefined
setProfile: React.Dispatch<React.SetStateAction<Profil | undefined>>
}
const ProfileContext = React.createContext<ProfileContext>({
openProfile: false,
setOpenProfile: () => {
return true
},
profile: undefined,
setProfile: () => {
return { profile: undefined }
},
})
export const useProfileContext = (): ProfileContext => React.useContext(ProfileContext)
interface ProfileContextProviderProps {
children: React.ReactNode
}
export const ProfileContextProvider = ({ children }: ProfileContextProviderProps): React.ReactElement => {
const [openProfile, setOpenProfile] = React.useState<boolean>(false)
const [profile, setProfile] = React.useState<Profil | undefined>(undefined)
const { loadProfile, createProfile, deleteProfile } = useProfile()
const loadProfileIntoContext = () => {
const userProfile = loadProfile()
userProfile.then((values) => {
setProfile(values)
console.log(profile)
})
}
loadProfileIntoContext()
return (
<>
<ProfileContext.Provider value={{ openProfile, setOpenProfile, profile, setProfile }}>
{children}
</ProfileContext.Provider>
</>
)
}

对于这些情况,您应该使用useEffect和一个空的深度数组

interface ProfileContext {
openProfile: boolean
setOpenProfile: React.Dispatch<React.SetStateAction<boolean>>
profile: Profil | undefined
setProfile: React.Dispatch<React.SetStateAction<Profil | undefined>>
}
const ProfileContext = React.createContext<ProfileContext>({
openProfile: false,
setOpenProfile: () => {
return true
},
profile: undefined,
setProfile: () => {
return { profile: undefined }
},
})
export const useProfileContext = (): ProfileContext => React.useContext(ProfileContext)
interface ProfileContextProviderProps {
children: React.ReactNode
}
export const ProfileContextProvider = ({ children }: ProfileContextProviderProps): React.ReactElement => {
const [openProfile, setOpenProfile] = React.useState<boolean>(false)
const [profile, setProfile] = React.useState<Profil | undefined>(undefined)
const { loadProfile, createProfile, deleteProfile } = useProfile()
const loadProfileIntoContext = () => {
const userProfile = loadProfile()
userProfile.then((values) => {
setProfile(values)
console.log(profile)
})
}

useEffect(() => {
loadProfileIntoContext()
}, [])
return (
<>
<ProfileContext.Provider value={{ openProfile, setOpenProfile, profile, setProfile }}>
{children}
</ProfileContext.Provider>
</>
)
}

最新更新