我目前正在实现 useSWR 以便从我的 Express 和 mongo-db 后端获取数据。我能够成功地从数据库中获取数据,没有问题。以下是我用来实现此目的的代码:
```//SWR method for hydration
const fetcher = (...args) => fetch(...args).then(res => res.json())
const { data, error } = useSWR('http://localhost:3000/appi/daily', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>```
然后可以使用以下方式访问:
data.currentInfo.username
其中用户名是集合中的字段之一。
当我尝试将此信息添加到状态挂钩中时,问题就出现了,然后返回错误,渲染的挂钩比之前的渲染期间更多。
拆除线路:
const[displayNumber] = useState(data.currentInfo.randomString)
任何使用状态变量 displayNumber 的行都可以完全修复错误。
我已在下面包含相关代码:
const fetcher = (...args) => fetch(...args).then(res => res.json())
const { data, error } = useSWR('http://localhost:3000/appi/daily', fetcher)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
const[displayNumber] = useState(data.currentInfo.randomString)
//handler function for changing state variable
function handleNumChange(event){
console.log(event.target.value);
setNumber(event.target.value);
}
return(
<div>
<div>
<Navbar className="navbar"/>
<h2>{data.currentInfo.username}</h2>
<h2>{displayNumber}</h2>
简而言之,我用 swr 提取数据,将此信息添加到状态变量中,然后用 h2 显示它。
有人能告诉我这种方法可能有什么问题吗?
我在网上搜索了错误,说它可能是由 useEffect 挂钩引起的,但我的代码中没有任何错误。
该错误描述您的挂钩比之前的渲染更多。如果您阅读了 React 文档,那么每次渲染时都应始终调用所有
useState
钩子。当您的代码具有额外的 useState
时,您不能有条件 useState
,如下所示:
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
这意味着如果没有
error
并且有 data
,则只会调用 const[displayNumber] = useState(data.currentInfo.randomString)
线。
编辑: 将其移至顶部通常可以解决您的问题。
const fetcher = (...args) => fetch(...args).then(res => res.json())
const { data, error } = useSWR('http://localhost:3000/appi/daily', fetcher)
//const[displayNumber] = useState(data.currentInfo.randomString) //Needs null checks ofcourse
//With null checks
const[displayNumber] = useState((data && data.currentInfo && data.currentInfo.randomString) || undefined)
//OR
//const[displayNumber] = useState(data?.currentInfo?.randomString)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>