有条件地渲染 useEffect fetch React

Conditionally render useEffect fetch React

制作视频游戏剪辑发布应用。我在后端有一个控制器,它将按照对剪辑的评论最多到最少的顺序给我剪辑。我想通过使用 select 标签(稍后我将添加更多过滤器)在正常排序数据和从最多到最少评论之间切换。我希望我可以根据来自 select 标记 onChange 的状态有条件地呈现这两个提取,但我得到了一个错误。

 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

这是我的代码。请注意,我只是用布尔值对其进行测试。

 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));
    }, []);
  }

如错误所述,您不能有条件地调用 useEffect。相反,无论如何调用它一次,并在该函数内查看是否需要获取剪辑或评论。

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
    }
}, []);