使用Wrrasters React组件
将SWR数据获取到我的React组件后,它会崩溃,如果我评论它,它可以正常工作。 遇到以下错误。
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.
我会在不计入行const {data} = usewr(`/api/views/$ {slug}`,fetcher)
该组件
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>
)
}
可能与此事实有关的事实方面 组件包含在另一个使用Getstatic Paths和GetStaticProps的组件中?
完整的代码库可以在此处找到: https://github.com/sennr-com/sennr-1952135/sennr-1952135/ >
After adding an SWR data fetch to my react component it crashes, if I comment it out it works fine.
I get the following error after uncommenting line 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.
The component
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>
)
}
Maybe it also has something to do with the fact that this component is included within another component that uses getStaticPaths and getStaticProps?
The full codebase can be found here: https://github.com/SennR-1952135/sennr
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题似乎是SWR的版本,我必须使用1.1.2或更低,但仍然不知道确切的原因,但它可以起作用。
The problem seemed to be with the version of swr, i had to use 1.1.2 or lower, still dont know the exact reason but it works.