Next.JS“比之前的渲染期间渲染了更多的钩子”

Nig*_*ypt 3 javascript reactjs next.js

我目前正在实现 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>```
Run Code Online (Sandbox Code Playgroud)

然后使用以下方式访问:

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>

Run Code Online (Sandbox Code Playgroud)

简而言之,我用 swr 提取数据,将此信息添加到状态变量,然后用 h2 显示它。

谁能告诉我这种方法可能有什么问题?

我在网上搜索了该错误,该错误说它可能是由 useEffect 挂钩引起的,但我的代码中没有任何错误。

Stu*_*tje 7

该错误描述了您比之前的渲染有更多的钩子。如果你阅读了 React 文档,useState就会发现每次渲染时都应该调用所有钩子。useState当您的代码具有以下额外的波纹管时,您不能有条件useState

if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div> 
Run Code Online (Sandbox Code Playgroud)

这意味着如果没有error并且只有只有data那么该线路const[displayNumber] = useState(data.currentInfo.randomString)才会被呼叫。

编辑: 将其移至顶部通常可以解决您的问题。

if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div> 
Run Code Online (Sandbox Code Playgroud)