使用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);
)
fetchUsers函数在这里被调用onclick:
<Box>
<Button
onClick= setShouldFetch(true)
>
View User
</Button>
</Box>
下面的代码块应该呈现检索到的API响应。如果setShouldFetch为true,则渲染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"
}
你想要条件数据获取
在你的例子中,我认为它可能是这样的:
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>
)
稍微讨论一下,对于声明式数据获取,在组件呈现时立即自动调用fetch除非是有条件的。在useSWR
的情况下,如果您的键(useSWR
的第一个参数)为null,或者是返回null的函数或抛出错误的函数,则不会自动获取。