我想用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;

当前回答

在我的例子中,这只是我的App.js上的这一行代码,导致了这个问题,让我在调试上浪费了10个小时。React Native和Expo不能告诉我这一点。我在StackOverflow和github上做了所有的事情,甚至在react页面上应该解决这个问题,但问题仍然存在。为了找到罪魁祸首,我不得不一点一点地把我的代码拆开

 **const window = useWindowDimensions();**

它是这样摆放的:

import * as React from 'react';
import { Text, View, StyleSheet, ImageBackground, StatusBar, Image, Alert, SafeAreaView, Button, TouchableOpacity, useWindowDimensions } from 'react-native';
import Constants from 'expo-constants';

import Whooksplashscreen11 from './Page1';
import Screen1 from './LoginPage';
import Loginscreen from './Login';
import RegisterScreen1 from './register1';
import RegisterScreen2 from './register2-verifnum';
import RegisterScreen3 from './register3';
import RegisterScreen4 from './register4';
import RegisterScreen5 from './register5';
import RegisterScreen6 from './register6';
import BouncyCheckbox from "react-native-bouncy-checkbox";
import LocationPermission from './LocationPermission.js'
import Selfieverif1 from './selfieverif1'
import Selfieverif2 from './selfieverif2'
import AddPhotos from './addphotos'


// You can import from local files
import { useFonts } from 'expo-font';

// or any pure javascript modules available in npm

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';


//FontAwesome
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab, } from '@fortawesome/free-brands-svg-icons'
import { faCheckSquare, faCoffee, faFilter, faSearch,  } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'
import Icon  from "react-native-vector-icons/FontAwesome5";

import MyTabs from './swipepage'

library.add(fab, faCheckSquare, faCoffee, faFilter, faSearch,);


const window = useWindowDimensions();
const Stack = createNativeStackNavigator();

function App() {
  return ( ....
)}

其他回答

你只能从React函数中调用钩子。点击这里阅读更多。

只需将Allowance类组件转换为功能组件。

Working CodeSandbox演示。

const Allowance = () => {
  const [allowances, setAllowances] = useState([]);

  useEffect(() => {
    fetch("http://127.0.0.1:8000/allowances")
      .then(data => {
        return data.json();
      })
      .then(data => {
        setAllowances(data);
      })
      .catch(err => {
        console.log(123123);
      });
  }, []);

  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 > {
      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;

在我的NextJs应用中,我也遇到了同样的问题。在我的例子中,我认为这是与缓存相关的问题。删除"后运行项目。“Next”文件夹修复了问题。我希望删除React中的构建文件夹也能起到同样的作用。

Bad:

import { useDispatch } from 'react';

好:

import { useDispatch } from 'react-redux';

我记得有一次我从“react”中导入了useDispatch,而不是从“react-redux”中导入。 这是很难弄清楚的,因为代码从每个角度都是正确的,我只是几个小时都猜不出来

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

所以,与其:

"type": "pwa-node",

它应该是:

"type": "node",

当我使用npm link安装我的本地库时,我遇到了这个问题,我使用cra构建了本地库。我在这里找到了答案。字面意思是:

当你使用npm link或类似的工具时,这个问题也会出现。 在这种情况下,您的捆绑器可能“看到”两个react -一个在应用程序中 文件夹和图书馆文件夹里的一个。假设'myapp'和'mylib' 是兄弟文件夹,一个可能的解决办法是运行'npm link . ./myapp/node_modules/react这应该使 库使用应用程序的React副本。

因此,运行命令:npm link <path_to_local_library>/node_modules/react,例如。在我的情况下NPM链接..项目目录下的/libraries/core/decipher/node_modules/react修复了这个问题。