使用useSWR从端点检索数据,但我收到了这个错误(我只想在onClick上检索数据)

"useSWR is called in function `fetchUsers` that is niether a React function component nor a custom React Hook function" Error 
const [shouldFetch,setShouldFetch] = useState(false)
const fetcher = (url) => axios.get(url).then((res) => res.data);
    const { data, error } = useSWR(shouldFetch ? "http://localhost:5000/users": null, fetcher);
    )

在此处onClick调用fetchUser函数:

        <Box>
        <Button
          onClick= setShouldFetch(true)
        >
          View User
        </Button>
      </Box>

下面的代码块应该呈现检索到的API响应.如果setShouldFetch为真,则呈现API响应,否则呈现其他内容.下面是我当前的实现,但它返回了一个错误 cannot read properties of undefined (reading 'name)

             <Typography
              >
                shouldFetch? data.name : Students Portal
              </Typography>

以下是预期的回应:

   {
        "name": [
            {
                "id": "8",
                "age": "10"
            },
            {
                "id": "4",
                "age": "11",
            }
        ],
        "id": "71"
    }

推荐答案

你想要conditional data fetching

在您的示例中,我认为可能是这样的:

const [shouldFetch,setShouldFetch] = useState(false)
const fetcher = (url) => axios.get(url).then((res) => res.data);
const { data, error } = useSWR(shouldFetch ? 'http://...' : null,fetcher)

return (
       <Box>
        <Button
          onClick={() => setShouldFetch(true)}
        >
          View User
        </Button>
      </Box>
)

为了稍微讨论一下这一点,对于声明性数据获取,当呈现102组件时,会立即自动调用获取,并使其具有条件.在useSWR的情况下,如果您的键(useSWR的第一个参数)是空的,或者是一个返回空的函数,或者是一个抛出错误的函数,那么它不会自动获取.

Javascript相关问答推荐

如何使用Echart 5.5.0创建箱形图

成帧器运动中的运动组件为何以收件箱开始?

按钮未放置在html dis位置

如何在RTK上设置轮询,每24小时

如何解决chrome—extension代码中的错误,它会实时覆盖google—meet的面部图像?'

Rehype将hashtag呈现为URL

在nextjs服务器端api调用中传递认证凭证

如何通过使用vanilla JS限制字体大小增加或减少两次来改变字体大小

实现JS代码更改CSS元素

为什么useState触发具有相同值的呈现

如何在不影响隐式类型的情况下将类型分配给对象?

构建器模式与参数对象输入

Socket.IO在刷新页面时执行函数两次

如何在尚未创建的鼠标悬停事件上访问和着色div?

如何在Jest中模拟函数

Chart.js Hover线条在鼠标离开时不会消失

扩散运算符未按预期工作,引发语法错误

每隔一行文本段落进行镜像(Boustrophedon)

在采购unpept-visalizations.js时遇到问题

我怎么才能拿到幼风登录?