错误:无效的挂钩调用。钩子只能在函数体内调用

时间:2021-06-05 22:23:26

标签: reactjs

我搜索了它,我想我正在打破 Hooks 的规则,但我不知道是哪一个 .. 你也能帮我解决它吗? 当我跟随反应路由器 (https://reactrouter.com/web/guides/quick-start/1st-example-basic-routing) 时,主页功能正常工作 我只是用这个家庭功能替换了它,它成功了

现在我想做的是从服务器请求数据并在react js中接收它,这样我就可以成功显示它

编辑:作为后端服务器,express 一切正常

enter image description here

import React, { Component } from "react";
import logo from "./logo.svg";

import "./App.css";

class App extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {
      user: "",
      body: ""
    };
  }
  componentDidMount() {
    var Vstate = Home();
    console.log(Vstate);
    this.setState({
      user: Vstate.user,
      body: Vstate.body
    });
  }

  render(){
    return (
      <div>
        <label className="username"> user is here {this.state.user}</label>
        <label className="body">body is here {this.state.message}</label>
      </div>
    );
  }
}

function Home() {

  const [data, setData] = React.useState(null);

  
  React.useEffect(() => {
    fetch("/api")
      .then((res) => res.json())
      .then((data) => {
        setData(data)
      });
      // console.log(data.message);
  }, []);
    return data;

}

function About() {
  const [data, setData] = React.useState(null);

   
  React.useEffect(() => {
    fetch("/s")
      .then((res) => res.json())
      .then((data) => {
        setData(data.message)
      });
    }, []);
    console.log(data);
    return <h2>{data}</h2>;
}

function Users() {
  return <h2>Users</h2>;
}

export default App;

2 个答案:

答案 0 :(得分:0)

在类组件的 drive 函数内部,您手动调用函数组件 (componentDidMount),而不是尝试使用 JSX(或 Home())呈现它。手动调用使用钩子的功能组件违反了钩子规则,就像错误信息所说的那样。

您需要在类组件的 React.createElement 方法返回的 JSX 中引用您的功能组件(或另一个功能组件返回的 JSX)。

答案 1 :(得分:0)

App转成函数组件,然后就可以使用hook了。

仅供参考的钩子通常遵循 use[theThingThatItDoes]

的命名约定

所以你可以这样写你的代码,它应该可以工作

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

import './App.css';

const App = () => {
  const {user, body} = useFetchData();

  return (
    <div>
      <label className='username'> user is here {user}</label>
      <label className='body'>body is here {body}</label>
    </div>
  );
};

function useFetchData() {
  const [data, setData] = React.useState({});

  useEffect(() => {
    fetch('/api')
      .then(res => res.json())
      .then(setData);
  }, []);

  return data;
}

export default App;