useswr 崩溃反应组件
useswr crashes react component
在我的 React 组件中添加 SWR 数据获取后它崩溃了,如果我注释掉它它工作正常。
取消注释行 const { data } = useSWR(`/api/views/${slug}`, fetcher)
后出现以下错误
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
组件
import { useEffect } from 'react'
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((r) => r.json())
export default function ViewCounter({
slug,
addView = false,
}: {
slug: string
addView?: boolean
}) {
const { data } = useSWR(`/api/views/${slug}`, fetcher)
// const viewCount = new Number(data?.total)
useEffect(() => {
console.log('ViewCounter useEffect', slug, addView)
const registerView = () =>
fetch(`/api/views/${slug}`, {
method: 'POST',
})
if (addView) {
registerView()
}
}, [slug])
// return `${viewCount > 0 ? viewCount.toLocaleString() : '–––'} views`
return (
<span className="flex items-center gap-1">
{data && data?.total}
</span>
)
}
也许这也与此组件包含在另一个使用 getStaticPaths 和 getStaticProps 的组件中有关?
完整的代码库可以在这里找到:https://github.com/SennR-1952135/sennr
问题好像出在swr的版本上,我必须使用1.1.2或更低版本,仍然不知道确切原因,但它有效。
在我的 React 组件中添加 SWR 数据获取后它崩溃了,如果我注释掉它它工作正常。
取消注释行 const { data } = useSWR(`/api/views/${slug}`, fetcher)
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
组件
import { useEffect } from 'react'
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((r) => r.json())
export default function ViewCounter({
slug,
addView = false,
}: {
slug: string
addView?: boolean
}) {
const { data } = useSWR(`/api/views/${slug}`, fetcher)
// const viewCount = new Number(data?.total)
useEffect(() => {
console.log('ViewCounter useEffect', slug, addView)
const registerView = () =>
fetch(`/api/views/${slug}`, {
method: 'POST',
})
if (addView) {
registerView()
}
}, [slug])
// return `${viewCount > 0 ? viewCount.toLocaleString() : '–––'} views`
return (
<span className="flex items-center gap-1">
{data && data?.total}
</span>
)
}
也许这也与此组件包含在另一个使用 getStaticPaths 和 getStaticProps 的组件中有关?
完整的代码库可以在这里找到:https://github.com/SennR-1952135/sennr
问题好像出在swr的版本上,我必须使用1.1.2或更低版本,仍然不知道确切原因,但它有效。