首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能在顶级调用React Hook "useState“

不能在顶级调用React Hook "useState“
EN

Stack Overflow用户
提问于 2021-05-18 13:39:00
回答 1查看 840关注 0票数 0

我是react的初学者。我正在尝试使用react-hooks将数据库的值从一个文件发送到另一个文件,并得到以下错误,有人能帮助我吗?

第5:41行:不能在顶层调用React Hook "useState“。React Hooks必须在React函数组件或自定义React Hook函数react-hooks/rules-of-hooks代码中调用:

代码语言:javascript
复制
import React, {useState, useEffect} from "react";

import Axios from "axios";

const [collegeList, setcollegeList]=useState([]);
useEffect(()=>{
    Axios.get("http://localhost:3001/api/get").then((response)=>{
        setcollegeList(response.data);
    });
}, []);

CollegeList = collegeList;
export default CollegeList;
EN

回答 1

Stack Overflow用户

发布于 2021-05-18 13:55:01

必须在react组件中使用react挂钩。我可以向你推荐两种方法来解决这个问题。

首先)在您的组件中进行

代码语言:javascript
复制
import React, {useState, useEffect} from "react";
import Axios from "axios";

function CollegeListComponent() {
const [collegeList, setcollegeList]=useState([]);

useEffect(()=>{
    Axios.get("http://localhost:3001/api/get").then((response)=>{
        setcollegeList(response.data);
    });
}, []);

return "YOUR VIEW ELEMENTS"

第二)使用它作为react钩子

代码语言:javascript
复制
import React, {useState, useEffect} from "react";
import Axios from "axios";

// making a custom react hook like this
function useCollegeList() {
   const [collegeList, setcollegeList]=useState([]);

   useEffect(()=>{
       Axios.get("http://localhost:3001/api/get").then((response)=>{
           setcollegeList(response.data);
       });
   }, []);

return { collegeList }

然后,您可以在组件中导入useCollegeList以使用它

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67580523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档