我是react的初学者。我正在尝试使用react-hooks将数据库的值从一个文件发送到另一个文件,并得到以下错误,有人能帮助我吗?
第5:41行:不能在顶层调用React Hook "useState“。React Hooks必须在React函数组件或自定义React Hook函数react-hooks/rules-of-hooks代码中调用:
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;发布于 2021-05-18 13:55:01
必须在react组件中使用react挂钩。我可以向你推荐两种方法来解决这个问题。
首先)在您的组件中进行
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钩子
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以使用它
https://stackoverflow.com/questions/67580523
复制相似问题