
使用 Next.js 和 SWR 在按钮点击时触发数据请求
在 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 Failed to load: {error.message};
if (isLoading) return Loading...;
return (
{data && Data: {JSON.stringify(data)}}
);
}
export default MyComponent;代码解释:
- useState: 使用 useState 创建一个名为 shouldFetch 的状态变量,初始值为 false。
- useSWR: useSWR 的 key 依赖于 shouldFetch 的值。只有当 shouldFetch 为 true 时,才会发起 /api/data 的请求。否则,useSWR 不会执行任何操作。
- handleClick: 按钮的 onClick 事件处理函数 handleClick 将 shouldFetch 设置为 true,从而触发 useSWR 发起请求。
- fetcher: 一个异步函数,负责实际的数据获取。
替代方案:使用 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 Failed to load: {error.message};
if (isLoading) return Loading...;
return (
{data && Data: {JSON.stringify(data)}}
);
}
export default MyComponent;代码解释:
- useState: 使用 useState 管理数据 (data)、加载状态 (isLoading) 和错误 (error)。
- handleClick: 按钮的 onClick 事件处理函数 handleClick 使用 fetch 发起 API 请求。
- 错误处理: 使用 try...catch 块来捕获请求过程中可能发生的错误,并更新 error 状态。
- 加载状态: 使用 setIsLoading 在请求开始前设置为 true,请求完成后设置为 false,以显示加载指示器。
注意事项:
- 确保你的 API 端点 /api/data 返回有效的 JSON 数据。
- 根据实际情况修改 fetcher 函数或 fetch 请求的配置,例如添加请求头、身份验证信息等。
- 如果需要更高级的错误处理,可以自定义错误对象并包含更多信息。
总结:
本教程介绍了两种在 Next.js 应用中,通过按钮点击事件触发数据请求的方法。第一种方法利用 SWR 的条件请求特性,避免了直接在事件处理函数中使用 Hook 的限制。第二种方法则直接使用 fetch 或 axios 发起请求,更加灵活,但需要手动处理缓存和重试等功能。选择哪种方法取决于你的具体需求和对 SWR 功能的依赖程度。










