组件中的多个 useEffect 不起作用

multiple useEffect in a component doesn't work

当我从单个 useEffect 调用 API 时,它工作得很好。但是当我试图从同一组件中的另一个 useEffect 调用另一个 API 时,它显示 error.

如果可以的话,请看看我在codesandbox上的项目。

import React, { useEffect, useState } from 'react';
import { Container, Row, Col } from 'react-bootstrap';

const TeacherDashboard = () => {
    // console.log(props)
    const [appointmentList, setAppointmentList] = useState([]);
    const [viewProfile, setViewProfile] = useState([]);
    console.log(viewProfile);
    useEffect(() => {
        async function loadData(){
            const response = await fetch('http://localhost:4200/appointments')
                const data = await response.json();
                setAppointmentList(data)
        }
        loadData()
    }, [appointmentList])

    useEffect(() => {
        async function proData() {
            const response = await fetch('http://localhost:4200/schedule')
            const data = await response.json();
            setViewProfile(data)
        }
        proData()
    }, [viewProfile])

    return (
        <Container>
            <Row>
                <Col>
                   {
                       appointmentList.map(app => 
                           <div style={{border: '1px solid blue'}}>
                               <li>Name : {app.name} </li>
                               <li>Id : {app.s_id} </li>
                               <li>Sec : {app.sec} </li>
                               <li>Email : {app.email} </li>
                               <li>Date & Time : {app.dateTime} </li>
                           </div>

                        )
                   }
                </Col>
            </Row>
        </Container>
    );
};

export default TeacherDashboard;

我不确定将 appointmentListviewProfile 状态都设置为 useEffect 挂钩的依赖数组的一部分的目的。当您直接更新 useEffect 挂钩中的相应状态时,它们最终都会导致无限循环。

据我所知,你只需要发出一次请求,因此你应该使用一个空数组作为依赖数组,这样两个请求只会在组件挂载时被调用。这是如何完成的:

useEffect(() => {
  async function proData() {
    const response = await fetch('http://localhost:4200/schedule')
    const data = await response.json();
    setViewProfile(data)
  }
  proData();
  async function loadData(){
    const response = await fetch('http://localhost:4200/appointments')
    const data = await response.json();
    setAppointmentList(data)
  }
  loadData();
}, []);