简体   繁体   中英

How to fix react Hook useEffect has missing dependencies

I have researched a little bit about this eslint error and have tried to implement the solutions explained in a few post. But actually they made things worse. Because, if I would accept having the warning in the console, my application then seems to work. As soon as I implement one of the suggested solutions, the app fails with errors telling me there is a problem with too many renders.

Basically, I have a list with regions and cities that are using "useState". When the page displays, I want to set a region as selected. And as the cities are a part of the region-variable, I also display the cities connected to the selected region. To make this happen, I am using useEffect. More or less in this way:

    const [regions, setRegions] = useState(
        {
            region: 'region1', id: 1, cities: {name: 'city1', id: 1}
            ,region: 'region2', id: 2, cities: {name: 'city2', id: 1}
        }
    );
    const updateCityList = () => {
        let found = regions.find(el => el.className === 'selectedRow');
        setCities(found.cities);
    }
    useEffect(() => {
        const newArr = [...regions];
        newArr.find(el => el._id === 1).className = 'selectedRow';
        setRegions(newArr);
        updateCityList();
    }, []); 

Now, in the console I see the warning:

React Hook useEffect has missing dependencies: 'regions' and 'updateCityList'. Either include them or remove the dependency array  react-hooks/exhaustive-deps

Putting the functions inside the useEffect's array, will cause the error with rerender. I also have tried using "useCallback". But I got similar errors. The warning does not seem to be suppressed using the "ignore next line". However, I would prefer to solve this warning rather then trying to hide a possible issue.

In this useEffect:

    useEffect(() => {
        const newArr = [...regions];
        newArr.find(el => el._id === 1).className = 'selectedRow';
        setRegions(newArr);
        updateCityList();
    }, []); 

You should add a flag to check if the effect has already ran once (return immediately if so), so the effect won't update regions state again causing infinite rendering.

Something like:

    useEffect(() => {
        if (!flag)
            flag = true;
        else
            return;
        <Your logic>
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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