有条件地渲染 useEffect fetch React

斯科茨代尔

制作视频游戏剪辑发布应用程序。我在后端有一个控制器,它将按照对剪辑的评论最多到最少的顺序为我提供剪辑。我想在正常排序数据之间切换,使用选择标签从最多评论到最少评论(稍后我将添加更多过滤器)。我希望我可以根据选择标记 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
    }
}, []);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

有条件地调用React Hook的“ useEffect”

React 不从 useEffect 内部的 fetch 渲染数据

React延迟后如何有条件地更改useEffect的状态?

有条件地调用 React Hooks "useState/useEffect/useCallback"

基于路由有条件地渲染 CSS (React)

有条件地渲染 React JS 中的元素?

在 React 组件中有条件地渲染 <td>

有条件地在react jsx中渲染className

如何在useEffect中更新状态的条件组件中有条件地渲染?

React useEffect挂钩中的Fetch API没有响应

有条件地反应useEffect hook加载快照

如何有条件地渲染使用钩子的React组件

React Bootstrap根据地图索引有条件地渲染

React 有条件地渲染一个 div

在React中有条件地在div周围渲染锚链接

在React中基于路由有条件地渲染组件

React JS在上传时有条件地渲染动画乐透组件

React有条件地在特定路径中渲染组件

React Native:如何有条件地渲染从调用 Firebase 函数的函数返回的值?

有条件地渲染JSX的React组件的更新周期如何表现?

基于状态在React JS中有条件地渲染内容

React js 有条件地将类渲染到特定的映射项

如何在React Native中有条件地从三个不同的选项进行渲染?

如何使用React有条件地渲染2个数据源中的数据

通过React useHistory传递道具时,如何有条件地渲染道具并检查未定义内容?

有条件地在React中进行所需的输入

在React中有条件地添加HTML属性

React Js有条件地应用类属性

React-native - 有条件地设置高度