
在 Next.js 应用中使用 SWR 进行数据获取非常方便,但直接在事件处理函数(如按钮点击事件)中使用 useSWR Hook 会导致 "Invalid hook call" 错误。这是因为 React Hooks 只能在函数组件或自定义 Hook 的顶层调用,而不能在条件语句、循环或嵌套函数中使用。
解决方案:利用 SWR 的条件请求
SWR 允许你通过传递 null 或 false 作为 key 来禁用请求。我们可以利用这个特性,结合一个状态变量来控制 useSWR 是否发起请求。
import useSWR from 'swr';
import { useState } from 'react';
const fetcher = async (url) => {
const res = await fetch(url);
if (!res.ok) {
const error = new Error('An error occurred while fetching the data.');
error.info = await res.json();
error.status = res.status;
throw error;
}
return res.json();
};
function MyComponent() {
const [shouldFetch, setShouldFetch] = useState(false);
const { data, error, isLoading } = useSWR(
shouldFetch ? '/api/data' : null, // 当 shouldFetch 为 true 时才发起请求
fetcher
);
const handleClick = () => {
setShouldFetch(true); // 点击按钮时将 shouldFetch 设置为 true
};
if (error) return <div>Failed to load: {error.message}</div>;
if (isLoading) return <div>Loading...</div>;
return (
<div>
<button onClick={handleClick}>Fetch Data</button>
{data && <div>Data: {JSON.stringify(data)}</div>}
</div>
);
}
export default MyComponent;代码解释:
替代方案:使用 fetch 或 axios 直接获取数据
如果不想使用 SWR 的缓存和自动重试功能,可以直接使用 fetch 或 axios 在事件处理函数中获取数据。
import { useState } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const handleClick = async () => {
setIsLoading(true);
try {
const res = await fetch('/api/data');
if (!res.ok) {
throw new Error('Failed to fetch data');
}
const jsonData = await res.json();
setData(jsonData);
setError(null);
} catch (err) {
setError(err);
setData(null);
} finally {
setIsLoading(false);
}
};
if (error) return <div>Failed to load: {error.message}</div>;
if (isLoading) return <div>Loading...</div>;
return (
<div>
<button onClick={handleClick}>Fetch Data</button>
{data && <div>Data: {JSON.stringify(data)}</div>}
</div>
);
}
export default MyComponent;代码解释:
注意事项:
总结:
本教程介绍了两种在 Next.js 应用中,通过按钮点击事件触发数据请求的方法。第一种方法利用 SWR 的条件请求特性,避免了直接在事件处理函数中使用 Hook 的限制。第二种方法则直接使用 fetch 或 axios 发起请求,更加灵活,但需要手动处理缓存和重试等功能。选择哪种方法取决于你的具体需求和对 SWR 功能的依赖程度。
以上就是使用 Next.js 和 SWR 在按钮点击时触发数据请求的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号