首页 > 解决方案 > 无法打破 Reactjs useEffect 无限循环

问题描述

我有一个useEffect()Auth0 用户作为依赖项。当用户登录并且用户对象可用时,组件会呈现,但它会导致无限循环,从而导致 API 调用被多次调用。该应用程序是一个使用 Stripe API 和 Mongodb 的简单发票仪表板。

仪表板.js

import React, {useEffect, useState} from "react";
import { useAuth0 } from "@auth0/auth0-react";
import axios from 'axios';
import LogRocket from 'logrocket';
// @material-ui/core
import { makeStyles } from "@material-ui/core/styles";
import Icon from "@material-ui/core/Icon";
import Button from '@material-ui/core/Button';

// core components
import GridItem from "components/Grid/GridItem.js";
import GridContainer from "components/Grid/GridContainer.js";
import Card from "components/Card/Card.js";
import CardHeader from "components/Card/CardHeader.js";
import CardIcon from "components/Card/CardIcon.js";
import CardFooter from "components/Card/CardFooter.js";
import Snackbar from "components/Snackbar/Snackbar.js";
import StorageIcon from '@material-ui/icons/Storage';
import MessageIcon from '@material-ui/icons/Message';
import styles from "assets/jss/material-dashboard-react/views/dashboardStyle.js";
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import 'react-notifications/lib/notifications.css';
import {NotificationContainer, NotificationManager} from 'react-notifications';
import * as _ from 'underscore'

export default function Dashboard() {

 


  


  // Abstracted Authentication variables
  const { user, isAuthenticated, isLoading,} = useAuth0(); // <-- user object

  // Initilizing the state as an empty array because response is an object that is an array of objects
  const [data, setData] = useState([{}]);
  const [paidData, setPaidData] = useState([{}]);
  const [loggedInUser, setLoggedInUser] = useState({});
  const [paidInvoiceUser, setPaidInvoiceUser] = useState({});
  const [reminder, setReminder] = useState(false);
  // Positioning State for notification
  const [tc, setTC] = useState(true);
  const [bl, setBL] = useState(true);

  // Tabs state
  const [value, setValue] = React.useState(0);

  // Styling
  const useStyles = makeStyles(styles);
  const classes = useStyles();  

  // Time Conversions
  const moment = require('moment'); 
  moment().format(); 

 



  async function fetPaidInvoices() {
    
    try {
      

      const url = `${process.env.REACT_APP_FETCH_PAID_INVOICES}`;
      const axiosConfig = {
        method: 'get',
        url,
      };
      const invoices = await  axios(axiosConfig).catch((e) => {console.log(e)});
      await setPaidData(invoices.data);
      console.log('[fetPaidInvoices] Paid invoices for user fetched from server');
    } catch (error) {
      
      console.log('[fetPaidInvoices]: An Error has occured', error)
    }
  }

 
  

  async function fetchUserInvoices() {
try {
     // Making a call to external api
    await fetch(`${process.env.REACT_APP_FETCH_USER_INVOICES}`)   
    .then(async (res) => {

      // Saving response to the invoiceResponse variable
      const invoiceResponse = await res.json();

      // Updating state to contain our object which is an array of objects
      setData(invoiceResponse);
      console.log('[fetchUserInvoices:', invoiceResponse);
      
    }).catch(err => err); 
    
} catch (error) {
  console.log(error);
}
   
  return;
 }

 
 
  // UseEffect that causes loop
  useEffect(() => {
    
    // setting the state to include the logged in user object to be sent to server.
    setLoggedInUser(user);
    setPaidInvoiceUser(user);
   
  }, [user])


  try {
    
    
    // sends call to backend to update database with any invoices that may be paid.
      updateDB();

      // executes POST call to backend with the logged in user.
       sendLoggedInUser(loggedInUser);
       sendPaidInvoiceUser(paidInvoiceUser);
 
     

  } catch (error) {
    console.log(error);
  }
  
useEffect(() => {
  
  // TODO User has to refresh to get invoices on dashboard, but it solved the Backend from being called multiple times.
  setTimeout(() => {

    // executes function that fetches invoices from DB after 100 milliseconds. Had to account for invoices to get fetched.
    fetchUserInvoices();
  }, 1000)

}, [])
 
  

  

  
    return(

     // UI
)
}

标签: javascriptnode.jsreactjsloopsexpress

解决方案


推荐阅读