发布
社区首页 >问答首页 >有条件渲染useEffect提取反应

有条件渲染useEffect提取反应
EN

Stack Overflow用户
提问于 2022-05-24 23:09:26
回答 1查看 67关注 0票数 0

制作一个视频游戏剪辑发布应用程序。我有一个控制器在后端,这将给我的剪辑的顺序,大多数评论剪辑到最少。我希望在数据正常排序之间进行切换,通过使用select标记(稍后我将添加更多过滤器)从大多数到最少的注释。我希望能够根据select标记onChange中的状态有条件地呈现这两个获取,但是我得到了一个错误。

代码语言:javascript
代码运行次数:0
复制
 Line 18:5:  React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render  react-hooks/rules-of-hooks
  Line 24:5:  React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render  react-hooks/rules-of-hooks

这是我的密码。注意,我只是在用布尔值测试它。

代码语言:javascript
代码运行次数:0
复制
 const boolean = true;
  if (boolean == true) {
    useEffect(() => {
      fetch("/clips")
        .then((r) => r.json())
        .then((data) => setClipData(data));
    }, []);
  } else {
    useEffect(() => {
      fetch("/most_comments")
        .then((r) => r.json())
        .then((data) => setClipData(data));
    }, []);
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-24 23:11:43

正如错误所述,不能有条件地调用useEffect。相反,不管调用它一次,在该函数中,查看是否需要获取剪辑或注释。

代码语言:javascript
代码运行次数:0
复制
useEffect(() => {
    if (boolean) {
        fetch("/clips")
            .then((r) => r.json())
            .then((data) => setClipData(data));
            // don't forget to .catch errors here
    } else {
        fetch("/most_comments")
            .then((r) => r.json())
            .then((data) => setClipData(data)); // did you mean to call setCommentsData or something here?
            // don't forget to .catch errors here
    }
}, []);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72370360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档