简体   繁体   English

尽管将参数传递给依赖数组,但反应 useEffect 导致无限重新渲染

[英]React useEffect causing infinite re-render despite passing argument to dependency array

The 'myPosts' has an object with multiple posts inside it.. I wanted the user profile to immediately show the post after it is uploaded so I passed 'myposts' in the dependency array. “myPosts”有一个 object,里面有多个帖子。我希望用户配置文件在上传后立即显示帖子,所以我在依赖数组中传递了“myposts”。

But the problem is that the component is re-rendering infinitely.但问题是组件正在无限地重新渲染。 How can I make it so that it re-renders once, only when a new post is uploaded?我怎样才能让它重新渲染一次,只有在上传新帖子时? I can't understand why passing 'myposts' in the array is causing infinite renders instead of only once.我不明白为什么在数组中传递 'myposts' 会导致无限渲染,而不仅仅是一次。

  const [myposts, setPosts] = useState([]);
  useEffect(() => {
  fetch('/mypost', {
    headers: {
     cookie: 'access_key',
    },
   })
     .then((res) => res.json())
     .then((data) => {
     // console.log(data);
     setPosts(data.myposts);
  });
 }, [myposts]);

When fetch resolves, it modifies myposts , which triggers a fetch because it is listed as dependency of useEffect, which modifies myposts , and so it continues...fetch解析时,它会修改myposts ,这会触发fetch因为它被列为 useEffect 的依赖项,它会修改myposts ,所以它继续......

It seems that myposts depends on the result of the fetch, not the other way around.似乎myposts取决于获取的结果,而不是相反。 So I would suggest removing myposts from the dependency list.所以我建议从依赖列表中删除myposts

The useEffect hook is called when myposts gets updated.myposts更新时调用 useEffect 挂钩。 In the final .then of your fetch, you're updating it via setPosts .在您获取的最后一个.then中,您正在通过setPosts对其进行更新。 The best way to fix this is by making the dependency array an empty array.解决此问题的最佳方法是将依赖数组设为空数组。
But this won't solve the issue of updating posts from the server, but this can also be done in a periodic function with setInterval .但这不会解决从服务器更新帖子的问题,但这也可以通过setInterval定期 function 完成。 This would result in something like the code below.这将导致类似于下面的代码。

const [myposts, setPosts] = useState([]);

const update = fetch('/mypost', {
  headers: {
    cookie: 'access_key',
  },
})
.then((res) => res.json())
.then((data) => {
  // console.log(data);
  setPosts(data.myposts);
});

useEffect(() => {
  update()
  const interval = setInterval(update, 30000)
  return () => clearInterval(interval)
}, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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