我想用React在一个表中显示一些记录,但我得到了这个错误:

无效的钩子调用。类的主体内部只能调用钩子 功能组件。这可能发生在以下情况之一 原因: React和渲染器的版本可能不匹配(比如React DOM) 你可能违反了胡克斯的规矩 你可能在同一个应用程序中有多个React副本,请参阅有关如何调试和调试的提示 解决这个问题。

import React, {
  Component
} from 'react';
import {
  makeStyles
} from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing(3),
    overflowX: 'auto',
  },
  table: {
    minWidth: 650,
  },
}));

class allowance extends Component {
  constructor() {
    super();
    this.state = {
      allowances: [],
    };

  }

  componentWillMount() {
    fetch('http://127.0.0.1:8000/allowances')
      .then(data => {

        return data.json();

      }).then(data => {

        this.setState({
          allowances: data
        });

        console.log("allowance state", this.state.allowances);
      })

  }



  render() {
    const classes = useStyles();
    return ( <
      Paper className = {
        classes.root
      } >
      <
      Table className = {
        classes.table
      } >
      <
      TableHead >
      <
      TableRow >
      <
      TableCell > Allow ID < /TableCell> <
      TableCell align = "right" > Description < /TableCell> <
      TableCell align = "right" > Allow Amount < /TableCell> <
      TableCell align = "right" > AllowType < /TableCell>

      <
      /TableRow> <
      /TableHead> <
      TableBody > {
        this.state.allowances.map(row => ( <
          TableRow key = {
            row.id
          } >
          <
          TableCell component = "th"
          scope = "row" > {
            row.AllowID
          } <
          /TableCell> <
          TableCell align = "right" > {
            row.AllowDesc
          } < /TableCell> <
          TableCell align = "right" > {
            row.AllowAmt
          } < /TableCell> <
          TableCell align = "right" > {
            row.AllowType
          } < /TableCell>                     <
          /TableRow>
        ))
      } <
      /TableBody> <
      /Table> <
      /Paper>
    );
  }

}

export default allowance;

当前回答

如果您正在使用mobx,并且您的功能组件被包装在mobx观察者函数中,也会发生此错误。如果是这种情况,请确保您使用的是mobx-react 6.0.0或更高版本。旧版本会将您的功能组件转换为隐藏的类,所有钩子都会因此错误而失败。

React Hooks Mobx:无效的钩子调用。钩子只能在函数组件的内部调用

其他回答

我的情况… 钩子中的解决方案

const [cep, setCep] = useState('');
const mounted = useRef(false);

useEffect(() => {
    if (mounted.current) {
        fetchAPI();
      } else {
        mounted.current = true;
      }
}, [cep]);

const setParams = (_cep) => {
    if (cep !== _cep || cep === '') {
        setCep(_cep);
    }
};

您可以将类组件转换为钩子,但Material v4有一个withStyles HOC。 https://material-ui.com/styles/basics/#higher-order-component-api 使用这个HOC,您可以保持代码不变。

我在一个自定义node_module上工作时遇到了同样的问题,并在cra(创建react应用程序)中使用npm link进行测试。

我发现在我的自定义节点包中,我必须添加一个peerDependencies

"peerDependencies": {
    "@types/react": "^16.8.6 || ^17.0.0",
    "react": "^17.0.0",
    "react-dom": "^17.0.0"
  },

我把它加到我的包里。json,然后重新构建我的自定义包。 然后在CRA,我吹走node_modules, re npm install, re -do npm link <package>,然后启动项目。

固定的一切!

我也有同样的问题,在编辑启动后得到了解决。Json文件,并通过从类型中删除'pwa-'来更改配置类型:

所以,与其:

"type": "pwa-node",

它应该是:

"type": "node",

当我在类组件中使用useLocation钩子时,我也有同样的问题

错误:

import React from "react";
import { useLocation } from "react-router-dom";

class ShowTheLocation extends React.Component {
  const location = useLocation();
  render() {
    return <div>You are now at {location.pathname}</div>;
  }
}

解决方案:我已经将类组件转换为功能组件,然后问题解决

import React from "react";
import { useLocation } from "react-router-dom";

const ShowTheLocation = () => {
  const location = useLocation();

  return <div>You are now at {location.pathname}</div>;
}