是什么导致了这里的无限循环?

eit6fx6z  于 2021-09-23  发布在  Java
关注(0)|答案(3)|浏览(309)

我是一个比较新的React者,我不完全理解在我的代码中哪里调用了重新渲染。我知道文件很大,很抱歉:(。我将移除那些我知道没有任何东西在不断被重新渲染的区域。
你知道在哪里,为什么吗?谢谢
代码:

function MeetupItem(props) {
    useCallback(() => {
        setAllParticipants(participantContext.getParticipants(props));
        try {
            fetch('http://localhost:3000/users')
                .then(response => {
                    return response.json();
                }).then(data => {
                    const users = [];
                    for (const key in data) {
                        const user = {
                            id: key,
                            ...data[key]
                        };
                        users.push(user);
                    };
                    setAllPossibleParticipants(allParticipants.filter(users));
                    console.log(allParticipants);
                })
        } catch (err) { console.log(err) };
    }, [participantContext, props, allParticipants]);

}

export default MeetupItem;```
bxpogfeg

bxpogfeg1#

当你使用 useCallback 您应该小心地提供依赖项数组。你已经准备好了 allParticipants 到依赖项数组,然后在代码中修改此变量的值!因此,在每次更改之后,回调将再次运行并导致无限循环!

bgibtngc

bgibtngc2#

在您的代码中,您正在设置 allParticipants 在的依赖项数组中 useCallback 同时在里面 useCallback 您正在更新的状态 allParticipants 这将导致无限循环,因为 useCallback 将在依赖项数组中的任何项发生更改时执行。
修改代码:

useCallback(() => {
        setAllParticipants(participantContext.getParticipants(props));
        try {
            fetch('http://localhost:3000/users')
                .then(response => {
                    return response.json();
                }).then(data => {
                    const users = [];
                    for (const key in data) {
                        const user = {
                            id: key,
                            ...data[key]
                        };
                        users.push(user);
                    };
                    setAllPossibleParticipants(allParticipants.filter(users));
                    console.log(allParticipants);
                })
        } catch (err) { console.log(err) };
    }, [participantContext, props]);

}

export default MeetupItem;

看看上面的代码是否解决了您的问题。

oxalkeyp

oxalkeyp3#

如果此行正在更新 allParticipantssetAllPossibleParticipants(allParticipants.filter(users));useCallback 会被再次召唤,就像你一样 allParticipants 因为这是依赖。

相关问题