关于调用react中钩子函数useState死循环的问题

刚接触react,遇到一些奇奇怪怪的问题,今天想通过调用get请求,从后端取到数据,然后存到状态里,结果出现了死循环,不断的发请求,代码如下

// 传入公司ID,获取到数据,将数据存到depts里面
// dept_get_list是我后台定义的一个方法,发送get请求,传入参数和一个回调函数,异步执行,所以我改变他的状态,从状态取值

const [depts, setDepts] = useState([])

const deptList = (orgId) => {
        dept_get_list({'orgId': orgId}, function (data) {
                if (data.content) {
                    setDepts(data.content)
                }
            }
        )
    }
deptList(orgId)
// 但当我执行deptList的时候,get请求疯狂的发请求,根本停不下来

解决方法:在useEffect里面写

import {useEffect, useState} from "react";
   useEffect(() => {
        deptList(orgId)
    },[orgId]);
// 第二个参数可以放多个,[orgId,],也就是当orgId相同时,只执行一次
原文地址:https://www.cnblogs.com/tuzaizi/p/15706525.html