Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early ret...

# [Uncaught Error: Rendered fewer hooks than expected. This may 
be caused by an accidental early return statement in React Hooks]
(https://stackoverflow.com/questions/53472795/uncaught-error-
rendered-fewer-hooks-than-expected-this-may-be-caused-by-an-
acc)

记录一下今天遇到的报错,查了很久才解决掉。

报错发生时,代码的具体情况:

在函数组件中使用了 useEffect、useState,在最后的 return 之前有一个 if 判断,这个判断 return 一个 ,大致如下

import React, {useState, useEffect} from 'react'
import ErrorView from './errorView'

const MeetingList = () => {

//... do something

if (/* ... */) {
    return (
      
    )
}

useEffect(()=>{
// do something
//...
},[/*...*/])


return (
    
//...
) export default MeetingList

报错大概意思是,因为 if 判断成立的时候,直接返回了 ErrorView,组件定义过的 useState,存在一部分没有被调用,导致最终 render 的 hooks 数量比预期的少,这样做不安全。

把 if 判断的这一段挪到最后面,改成了下面这样,报错解决掉了
...
...
...
if (/* ... */) {
    return (
      
    )
}

return (
    
//...
) export default MeetingList

参考链接:https://stackoverflow.com/questions/53472795/uncaught-error-rendered-fewer-hooks-than-expected-this-may-be-caused-by-an-acc

你可能感兴趣的:(Uncaught Error: Rendered fewer hooks than expected. This may be caused by an accidental early ret...)