react 如何定时刷新组件

2021-12-17 11:16:35 +08:00
 fangwenxue
const Posts = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    const getPosts = async () => {
      const resp = await fetch(API);
      const postsResp = await resp.json();
      setPosts(postsResp);
    };

    getPosts();
  }, []);

  return '';
};

export default Posts;

如何定时刷新 posts 的数据?

1210 次点击
所在节点    问与答
4 条回复
noe132
2021-12-17 11:37:19 +08:00
setTimeout / setInterval
lvdb
2021-12-17 13:11:10 +08:00
你这个 getposts 如果其他地方没用到,是不需要定义的,直接 async()=>{...}()
br_wang
2021-12-17 17:44:48 +08:00
1. 定义一个 state ,比如 refreshCount;
2. refreshCount 并声明为 effect 的依赖,利用 setRefreshCount 变更 refreshCount 值触发 effect 重新执行;
3. 可以 setTimeout 或 setInterval ,周期性调用 setRefreshCount 实现刷新;
4. 也可以把 setRefreshCount 绑到按钮上,手动触发刷新;
5. 注意竞速问题。
baolinliu442k
2021-12-17 18:15:58 +08:00
setTimeOut(()->{
getPosts();
}, time)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/822768

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX