在第二位。useEffect
我想使用来自第一个useEffect
的resume.id
返回experiences
。但我猜他们在同一时间工作,所以在第一个useEffect
中返回resume
之前,第二个正在工作,它返回undefined
。我该如何解决这个问题,或者有什么方法可以编写更好的代码吗?
const { authUser } = useSelector((state) => state.auth);
const [resume, setResume] = useState({});
const [experience, setExperience] = useState([]);
let resumeService = new ResumeService();
let resumeExperienceService = new ResumeExperienceService();
useEffect(() => {
resumeService
.getResumeByCandidateId(authUser.id)
.then((result) => setResume(result.data.data[0]));
}, []);
useEffect(() => {
resumeExperienceService
.getExperiencesByResumeId(resume.id)
.then((result) => setExperience(result.data.data));
}, []);
您应该将名为"resume"的状态添加到useEffect中。这意味着第二次useEffect将在每次setResume调用后运行
const { authUser } = useSelector((state) => state.auth);
const [resume, setResume] = useState({});
const [experience, setExperience] = useState([]);
let resumeService = new ResumeService();
let resumeExperienceService = new ResumeExperienceService();
useEffect(() => {
resumeService
.getResumeByCandidateId(authUser.id)
.then((result) => setResume(result.data.data[0]));
}, []);
useEffect(() => {
resumeExperienceService
.getExperiencesByResumeId(resume.id)
.then((result) => setExperience(result.data.data));
}, [resume]);