javascript 如何在使用Dispatch时阻止页面呈现?

sf6xfgos  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(91)

在我用React开发的项目中,我想在第一次进入页面时获取用户信息并将其发送给Redux,但当我在获取数据后使用dispatch时,页面进入了一个无限循环。我如何防止这种情况?
这是我的代码:

import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { SET_CANDIDATE_PROFILE_DETAILS } from '@/store/modules/candidate';

import CareerGoalSection from '@/components/profilDetail/CareerGoalSection';
import DocumentSection from '@/components/profilDetail/DocumentSection';
import EducationSection from '@/components/profilDetail/EducationSection';
import LanguageSection from '@/components/profilDetail/LanguageSection';
import ProfilCardSection from '@/components/profilDetail/ProfilCardSection';
import ReferencesSection from '@/components/profilDetail/ReferencesSection';
import SkillsSection from '@/components/profilDetail/SkillsSection';
import WorkExperienceSection from '@/components/profilDetail/WorkExperienceSection';
import ProfilDetailLayout from '@/layouts/ProfilDetailLayout';
import { useTranslation } from 'react-i18next';
import { authSelector } from '@/store/modules/auth';
import { candidateService } from '@/services/candidate.service';

interface ProfileDetailViewProps {
  hideNavFooter: boolean;
}

const ProfileDetailView: React.FC<ProfileDetailViewProps> = ({ hideNavFooter }) => {
  const { t } = useTranslation();
  const { decodedToken } = useSelector(authSelector);
  const candidateId = Number(decodedToken?.CandidateId);
  const dispatch = useDispatch();

  const getProfileDetails = async () => {
    try {
      const details = await candidateService.fetchCandidateProfileDetails(candidateId);
      dispatch(SET_CANDIDATE_PROFILE_DETAILS(details));
    } catch (error) {
      console.error('Error fetching profile details:', error);
    }
  };

  useEffect(() => {
    if (candidateId) {
      getProfileDetails();
    }
  }, [candidateId]);
  
  return (
    <ProfilDetailLayout title={t('profileDetails.name')} showNavAndFooter={!hideNavFooter}>
      <ProfilCardSection />
      <CareerGoalSection />
      <WorkExperienceSection/>
      <EducationSection/>
      <LanguageSection/>
      <SkillsSection/>
      <DocumentSection />
      <ReferencesSection />
    </ProfilDetailLayout>
  );
};

字符串

7lrncoxx

7lrncoxx1#

在useEffect钩子中调用getProfileDetails函数,它通过分派一个action来修改Redux状态。这会触发组件的重新渲染,并且由于useEffect钩子依赖于candidateId,它会创建一个无限循环。为了防止这种情况,您可以添加一个条件来检查在分派action之前是否已经获取了profile详细信息。

相关问题