Unhandled promise rejection: Error: Invalid hook call. Hooks can only be called inside of the body of a function component

Unhandled promise rejection: Error: Invalid hook call. Hooks can only be called inside of the body of a function component

所以,我从 Drawer.Navigator

的 drawerContent 中获得了这个组件 SidebarMenu

    const SidebarMenu: React.FC<SidebarMenuProps> = (props) => {
    
      return (
        <View style={{ flex: 1 }}>
    
          <DocenteMenu />
    
          <DrawerContentScrollView {...props}>
            <View style={styles.itemContent}>
              <MenuItem label="Home" icon="home" pageName="Home" {...props} />
              <MenuItem label="Chamada eletrônica" icon="edit" pageName="CallList" {...props} />
              <MenuItem label="Horário aula" icon="calendar" pageName="ClassSchedule" {...props} />
              <MenuItem label="Diário eletrônico" icon="book-open" pageName="ClassDiary" {...props} />
              <MenuItem label="Agendamento prova" icon="file-plus" pageName="TestSchedule" {...props} />
              <MenuItem label="Relação de alunos" icon="users" pageName="StudentsList" {...props} />
              <MenuItem label="Holerite" icon="file-text" pageName="Payslip" {...props} />
            </View>
          </DrawerContentScrollView>
    
          <View style={styles.logoutContent}>
            <MenuItem label="Sair" icon="log-out" />
          </View>
        </View>
      );
    }
    
    export default SidebarMenu;

我正在尝试 return 来自组件 DocenteMenu 的视图,但在那一刻 return 出错了。我已经尝试将此函数转换为“导出默认函数”并且return同样的错误


interface TeacherProps {
  COD_FUNCIONARIO: string,
  NOME_FUNC: string;
  DTA_NASC: Date;
  CPF: string;
  FOTO: string;
}
const DocenteMenu = () => {

  const [user, setUser] = useState<TeacherProps | null>();

  useEffect(function setUserProps() {

    const {docente} = useAuth();

    setUser(docente);

  }, []);

  return(
    <View style={styles.teacherInfo}>
      <Image
        style={styles.avatar}
        source={{ uri: user?.FOTO }}
      />
        <Text style={styles.teacherName}>{user?.NOME_FUNC}</Text>
        <Text style={styles.teacherCode}>{user?.COD_FUNCIONARIO }</Text>
    </View>
  );
}

export default DocenteMenu;

必须在 Function Componentanother custom hook 的顶层调用 React Hooks,因此将您的代码更改为这样就可以了:

const { docente } = useAuth();
useEffect(function setUserProps() {
  setUser(docente);
}, []);

关于hooks的规则也看了官方文档:https://reactjs.org/docs/hooks-rules.html

最好的做法是为 useEffect 使用简单的回调,不要给它起这样的名字:

const { docente } = useAuth();
useEffect(() => {
  setUser(docente);
}, []);