Next.JS“比上一次渲染期间渲染了更多的钩子”

时间:2020-08-06 10:40:21

标签: 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>```

然后使用以下命令访问它:

data.currentInfo.username 其中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挂钩引起的,但是我的代码中没有任何错误。

1 个答案:

答案 0 :(得分:0)

该错误说明您的钩子比以前的渲染器多。如果您阅读了react docs,所有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>