import { useCallback, useState, useEffect } from 'react'
import Axios from 'axios'
interface match {
params: {
[key: string]: string
}
}
function useRouteMatch(url: string): match {
return {
params: {
id: `100${url}`
}
}
}
function useTestHook() {
const [, setUserDetail] = useState()
const routeMatch: match | null = useRouteMatch("/user/detail/:id")
const fetchData = useCallback(() => {
Axios.get(`/api/admin/user/get?id=${routeMatch?.params.id}`)
.then((r) => { setUserDetail(r.data.user) })
}, [routeMatch])
useEffect(() => { fetchData() }, [fetchData])
}
我简单补全了一下一个代码,我觉得吧,你这 setUserDetail 是useState闭包产生的,每一次都不一样,不应该把它作为依赖项,应该作为依赖项的是routeMatch把,不然每次渲染,useState生成新的setUserDetail函数,新的setUserDetail函数又触发fetchData去执行setUserDetail函数导致重新渲染一遍
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…