组件中的多次useEffect不起作用

时间:2020-06-05 06:51:23

标签: reactjs api react-hooks use-effect

当我从单个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;

1 个答案:

答案 0 :(得分:1)

我不确定同时设置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();
}, []);