钩子只能在函数组件的主体内部调用.(fb.me/react-invalid-hook-call) [英] Hooks can only be called inside the body of a function component. (fb.me/react-invalid-hook-call)

查看:31
本文介绍了钩子只能在函数组件的主体内部调用.(fb.me/react-invalid-hook-call)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import  { useEffect } from "react";

export const Routes = () => {
  useEffect(() => {
    console.log("red")
  }, []);

  const a = [{ name: "sathish" }];
  const b = [{ name: "pandi" }];
  const c = [{ name: "suren" }];
  if (false) {
    return a;
  } else {
    return b;
  }
};

使用这段代码,我有错误,如 × Hooks 只能在函数组件的主体内调用.

With this code I have error like × Hooks can only be called inside the body of a function component.

推荐答案

从技术上讲,您缺少 2 个重要步骤,import React 部分和返回 JSX.

Technically you are missing 2 important steps, the import React part and returning JSX.

您可以采取以下措施使其发挥作用:

What you can do to make it work is the following:

import React, { useEffect } from 'react';

export const Routes = () => {
  useEffect(() => {
    console.log("red")
  }, []);

  const a = [{ name: "sathish" }];
  const b = [{ name: "pandi" }];
  const c = [{ name: "suren" }];

  return a.map((e, i) => <span key={i}>{e.name}</span>);
};

另外我添加了一个Array.prototype.map() 元素中表示数组中的名称.对于代码示例,我删除了您的 if 语句.

Additionally I have added an Array.prototype.map() to represent the name from your array in a <span> element. For the code sample I have removed your if statement.

更新:

此外,根据评论,该问题与在代码中调用 Admin 组件之外的 Routes 组件有关.

Also based on the comments the issue is related to calling outside of Admin component the Routes component in your code.

您还需要做什么才能使其包含到 Admin 组件中的 render 功能如下:

What you need to do also to make it work to include into the Admin component render function as the following:

class Admin extends Component {
   // rest of your code

   render() {
      return <>
         {/* rest of the code */}

         <Routes />
      </>
   }
}

我希望这会有所帮助!

这篇关于钩子只能在函数组件的主体内部调用.(fb.me/react-invalid-hook-call)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆