Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

React hooks添加依赖项导致无限循环的问题?

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); }); }
, [setUserDetail]);

useEffect(() => { fetchData(); }, [fetchData]);

此时eslint警告需要在fetchData的第二个参数中添加routeMatch的依赖,但是routerMatch在每一次渲染后都会引发再次渲染,于是产生无限循环 如何解决这个问题?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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函数导致重新渲染一遍


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...