×错误:无效的挂接调用-没有版本问题或多个React实例

问题描述

编辑 从应用中删除组件也摆脱了错误

我正在尝试使用useEffect钩子获取一个渲染,并且不断出现此错误

Error: Invalid hook call. Hooks can only be called
inside of the body of a function component.
 4 | 
   5 | const Students = ({students,setStudents}) => {
   6 | 
>  7 | useEffect(() =>{
   8 |     fetch('http://localhost:5000/students')
   9 |     .then(response => response.json())
  10 |     .then(json => setStudents(json))

我已经检查了React版本/复制问题,但似乎还可以,所以它一定在某个地方,但我看不到-这是组件:

import React,{ useEffect } from 'react';
import NewStudentCard from './NewStudentCard'


function Students ({students,setStudents}){

useEffect(() =>{
    fetch('http://localhost:5000/students')
    .then(response => response.json())
    .then(json => console.log(json))
},[])

    return (
        <ul>
            <NewStudentCard/>
        </ul>
        )
    }

export default Students

试图重命名状态并将其直接设置在组件中-仍然会收到错误

import React,{useState,useEffect } from 'react';
import NewStudentCard from './NewStudentCard'


const Students = () => {
const [pupils,setPupils] = useState([]);

useEffect(() =>{
    fetch('http://localhost:5000/students')
    .then(response => response.json())
    .then(json => setPupils(json))
},[pupils])

    return (
        <ul>
            <NewStudentCard/>
        </ul>
        )
    }

export default Students

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)