Dan*_*gon 8 reactjs fetch-api next.js swr
我正在使用 SWR 获取数据来填充表。我正在使用以下代码:
const { data: items, error } = useSWR(fetchAllItems.name, fetchAllItems)
Run Code Online (Sandbox Code Playgroud)
fetcher 函数看起来像这样
async function fetchAllItems() {
const response = await fetch('http://localhost:3000/items')
const data = await response.json()
return data
}
Run Code Online (Sandbox Code Playgroud)
该表还具有添加新项目的选项。创建新项目后,我调用 mutate 让 SWR 获取新数据。在开发模式下运行它时,一切都很好,但是当使用 next start 而不是 next dev 时,它不会获取数据。在网络选项卡中,它显示 0 个请求,因此看起来 fetcher 函数从未被调用。
获取数据的服务器运行正常。我已经使用邮递员对此进行了测试,它返回了所有项目。也可以从下一个应用程序访问它,因为创建新项目效果很好。
编辑:经过更多调试后,我将范围缩小到这样一个事实:当使用 next start 而不是 next dev 时,SWR 永远不会验证。
编辑2:可以在此处找到具有最小可重现示例的codesandbox https://codesandbox.io/s/elated-cherry-3ugqyi?file=/package.json。De Codesandbox 使用(调用下一个开发)运行程序npm run dev,因此一切正常。但是,当使用npm run build && npm run startuseSWR 运行它时,不再调用 fetcher 函数。
编辑3:我已经解决了这个问题,但不明白如何解决。我将 fetcher 函数更改为以下内容:
function fetchAllItems() {
return fetch('http://localhost:3000/items').then((res) => res.json())
}
Run Code Online (Sandbox Code Playgroud)
fetcher 函数现在不再是异步的,但它仍然返回一个 Promise(因为 fetch 返回一个 Promise)。如果有人能解释为什么这段代码的行为与之前的不同,那就太好了。
你的 fetcher 函数照原样就可以了。出现此问题的原因是在生产版本中fetchAllItems.name解析为空字符串'',这意味着useSWR不会调用 fetcher 函数,因为key参数是假值。
您有两种选择来解决问题。
useSWR密钥只需使用字符串key作为useSWR. 我推荐这种方法,因为使用fetchAllItems.name可能并不总是返回生产中的预期值。
const { data: items, error } = useSWR('fetchAllItems', fetchAllItems)
Run Code Online (Sandbox Code Playgroud)
fetchAllItems使用函数的命名函数格式fetchAllItems,而不是箭头函数。async当您定义不带/的新函数时,这可能是为您解决问题的原因await。
export async function fetchAllItems() {
const response = await fetch('http://localhost:3000/items')
const data = await response.json()
return data
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9728 次 |
| 最近记录: |