React useEffect hook 无限循环

React useEffect hook infinity loop

我在尝试使用 useEffect 挂钩获取和设置数据时一直遇到无限循环。我尝试了 3 种 hook 变体,它们都产生了一个循环,我该如何阻止这种情况发生?

useEffect(() => {
        (async () => {
            PostApi.getPostsByUser(auth.user._id, auth.token).then(response => setPosts(response))
        })()
    })
useEffect(() => {
        (async () => {
            PostApi.getPostsByUser(auth.user._id, auth.token).then(response => setPosts(response))
        })()
    },[])
useEffect(() => {
        (async () => {
            PostApi.getPostsByUser(auth.user._id, auth.token).then(response => setPosts(response))
        })()
    },[profile.posts])

编辑:这是PostApi.getPostsByUser代码

getPostsByUser: (userId, token) => {
        return(
            axios
            .get("/api/posts/by/" + userId, {
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    Authorization: "Bearer " + token
                }
            })
            .then(response => {
                console.log("Posts by User");
                console.log(response.data);
                return response.data;
            })
            .catch(err => console.log(err))
        )
    }

编辑:函数组件代码:

const Posts = () => {
    const [{auth}] = useAuth();
    const [{profile},, setPosts] = useProfile()

    useEffect(() => {
        PostApi.getPostsByUser(auth.user._id, auth.token)
        .then(response => setPosts(response));
    },[]);

    console.log(profile)
    return(
        <div className="User-Post">
            <div className="New-Post">
                <NewPost />
            </div>
            <div className="User-Posts-Content">
                {
                    profile.posts ? profile.posts.map((item, key) => {
                        return <Post post={item} key={key} />
                    }) : null
                }
            </div>
        </div>
    )
}

export default Posts

变化:

const [auth] = useAuth();
const [profile, setPosts] = useState();


const setPosts = posts => { setPosts(state => ({ ...state, profile: { 
             ...state.profile, posts: posts } })) } 


getPostsByUser: (userId, token) => {
        return(
            axios
            .get("/api/posts/by/" + userId, {
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    Authorization: "Bearer " + token
                }
            });
    }

useEffect(() => {
            PostApi.getPostsByUser(auth.user._id, auth.token)
            .then(response => setPosts(response.data));     
     },[]);

你可以这样试试

useEffect(() => {
  const get = async () => {
    const response = await PostApi.getPostsByUser(auth.user._id, auth.token);
    setPosts(response);
  }
  get();
},[]);

这对我有用……也是最简单的解决方案

  const [toggle, setToggle] = useState(false);
  useEffect(() => {
          (async () => {
              PostApi.getPostsByUser(auth.user._id, auth.token).then(response => setPosts(response))
          })()
      },toggle)