useEffect导致无限循环

时间:2019-11-30 18:16:06

标签: react-hooks

我搜索SO帖子“ useEffect导致无限循环”,并且看来还有36篇关于此的SO帖子。大多数答案都说要传入依赖项数组。像这样...

  useEffect(() => {
    // do something and then do ...
    setMatch(match);
  },[match]);

这就是我尝试过的。我尝试过的所有useEffect()仍然给我无限循环。

我已经尝试过了(没有依赖项数组)

   useEffect(()=> {

        const url = 'http://localhost:8000/rest-auth/user/';
        const withCredentials = true;
        const method = 'get';
        axios.request({method, url, withCredentials}).then(response => {
            setAppUser({...appUser, ...response.data});
            setLoggedIn(true);
        })
    });

我已经尝试过这个(空依赖数组)

   useEffect(()=> {

        const url = 'http://localhost:8000/rest-auth/user/';
        const withCredentials = true;
        const method = 'get';
        axios.request({method, url, withCredentials}).then(response => {
            setAppUser({...appUser, ...response.data});
            setLoggedIn(true);
        })
    }, []);

我已经尝试过(将appUser放入依赖项数组)

   useEffect(()=> {

        const url = 'http://localhost:8000/rest-auth/user/';
        const withCredentials = true;
        const method = 'get';
        axios.request({method, url, withCredentials}).then(response => {
            setAppUser({...appUser, ...response.data});
            setLoggedIn(true);
        })
    }, [appUser]);

更新:我尝试过:

   useEffect(()=> {

        const url = 'http://localhost:8000/rest-auth/user/';
        const withCredentials = true;
        const method = 'get';
        axios.request({method, url, withCredentials}).then(response => {
            setAppUser((appUser) => ({...appUser, ...response.data}));
            setLoggedIn(true);
        })
    }, []);

以上四种方法都会导致无限循环。

0 个答案:

没有答案