简体   繁体   English

无法打破 Reactjs useEffect 无限循环

[英]Cant break Reactjs useEffect infinite loop

I have a useEffect() that has the Auth0 user as a dependency.我有一个useEffect()将 Auth0 用户作为依赖项。 When the user logs in and the user object is available the component renders, but it's causing an infinite loop which causes the API calls to be called multiple times.当用户登录并且用户对象可用时,组件会呈现,但它会导致无限循环,从而导致多次调用 API 调用。 The app is a simple invoice dashboard that uses the Stripe API and Mongodb.该应用程序是一个使用 Stripe API 和 Mongodb 的简单发票仪表板。

Dashboard.js仪表板.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 ) }

Update the state only if those state values are empty or null仅当这些状态值为空或 null 时才更新状态

 useEffect(() => {
    if(loggedInUser === "" || paidInvoiceUser === ""){
        setLoggedInUser(user);
        setPaidInvoiceUser(user);
    }   
  }, [user])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM