React Context 无限期地调用函数

React Context calling function indefinitely

我有这个从上下文中加载的配置文件,但它一遍又一遍地调用该函数。如何让它只被调用 一次 或仅在 需要 时被调用。 例如,我有 2 个模态框,其中一个在不存在配置文件时被调用,另一个在配置文件存在时被调用。但是当调用第二个模式时,我看到配置文件被一遍又一遍地调用,但我希望它只被调用 onLoad 并且当配置文件发生更改时(更新,删除配置文件)。

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 和一个空的 deps

数组
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>
    </>
  )
}