admin管理员组

文章数量:1125714

I want to show some records in a table using React but I got this error:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See for tips about how to debug and fix this problem.
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;

I want to show some records in a table using React but I got this error:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See for tips about how to debug and fix this problem.
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;
Share Improve this question edited Mar 15, 2024 at 12:49 userlond 3,8182 gold badges40 silver badges55 bronze badges asked Jun 19, 2019 at 8:57 lwinlwin 4,4506 gold badges30 silver badges49 bronze badges 2
  • just a note, This error appears when instead of calling component like <Component prop1={prop1} /> if its written like a function call Component(prop1) then also same error will appear. I did this mistake when converting a util function into a functional component and forgetting to change the calling line. – Vikas Acharya Commented Dec 13, 2023 at 8:48
  • In my case I had other react packages (react-dom, react-router, etc.) in my devDependencies. Moving them to the scripts section along witht the main react package solved this. – David G Commented Jul 12, 2024 at 18:24
Add a comment  | 

58 Answers 58

Reset to default 1 2 Next 223

I had this issue when I used npm link to install my local library, which I've built using cra. I found the answer here. Which literally says:

This problem can also come up when you use npm link or an equivalent. In that case, your bundler might “see” two Reacts — one in application folder and one in your library folder. Assuming 'myapp' and 'mylib' are sibling folders, one possible fix is to run 'npm link ../myapp/node_modules/react' from 'mylib'. This should make the library use the application’s React copy.

Thus, running the command: npm link <path_to_local_library>/node_modules/react, eg. in my case npm link ../../libraries/core/decipher/node_modules/react from the project directory has fixed the issue.

You can only call hooks from React functions. Read more here.

Just convert the Allowance class component to a functional component.

Working CodeSandbox demo.

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;

You can use "export default" by calling an Arrow Function that returns its React.Component by passing it through the MaterialUI class object props, which in turn will be used within the Component render ().

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}

export default () => {
    const classes = useStyles();
    return (
        <AllowanceClass classes={classes} />
    )
}

For me , the error was calling the function useState outside the function default exported

React linter assumes every method starting with use as hooks and hooks doesn't work inside classes. by renaming const useStyles into anything else that doesn't starts with use like const myStyles you are good to go.

Update:

makeStyles is hook api and you can't use that inside classes. you can use styled components API. see here

Yesterday, I shortened the code (just added <Provider store={store}>) and still got this invalid hook call problem. This made me suddenly realized what mistake I did: I didn't install the react-redux software in that folder.

I had installed this software in the other project folder, so I didn't realize this one also needed it. After installing it, the error is gone.

This error can also occur when you make the mistake of declaring useDispatch from react-redux the wrong way: when you go:
const dispatch = useDispatch instead of:
const dispatch = useDispatch(); (i.e remember to add the parenthesis)

add this to your package.json

"peerDependencies": {
   "react": ">=16.8.0",
   "react-dom": ">=16.8.0"
}

source:https://robkendal.co.uk/blog/2019-12-22-solving-react-hooks-invalid-hook-call-warning

In my case, I was passing Component Name in FlatList's renderItem prop instead of function. It was working earlier as my component was a functional component but when I added hooks in it, it failed.

Before:

    <FlatList
        data={memberList}
        renderItem={<MemberItem/>}
        keyExtractor={member => member.name.split(' ').join('')}
        ListEmptyComponent={
          <Text style={{textAlign: 'center', padding: 30}}>
            No Data: Click above button to fetch data
          </Text>
        }
      />

After:

    <FlatList
        data={memberList}
        renderItem={({item, index}) => <MemberItem item={item} key={index} />}
        keyExtractor={member => member.name.split(' ').join('')}
        ListEmptyComponent={
          <Text style={{textAlign: 'center', padding: 30}}>
            No Data: Click above button to fetch data
          </Text>
        }
      />

I have just started using hooks and I got the above warning when i was calling useEffect inside a function:

Then I have to move the useEffect outside of the function as belows:

 const onChangeRetypePassword = async value => {
  await setRePassword(value);
//previously useEffect was here

  };
//useEffect outside of func 

 useEffect(() => {
  if (password !== rePassword) {
  setPasswdMismatch(true);

     } 
  else{
    setPasswdMismatch(false);
 }
}, [rePassword]);

Hope it will be helpful to someone !

complementing the following comment

For those who use redux:

class AllowanceClass extends Component{
    ...
    render() {
        const classes = this.props.classes;
        ...
    }
}
    
const COMAllowanceClass = (props) =>
{
    const classes = useStyles();
    return (<AllowanceClass classes={classes} {...props} />);
};

const mapStateToProps = ({ InfoReducer }) => ({
    token: InfoReducer.token,
    user: InfoReducer.user,
    error: InfoReducer.error
});
export default connect(mapStateToProps, { actions })(COMAllowanceClass);

Different versions of react between my shared libraries seemed to be the problem (16 and 17), changed both to 16.

Happens to me when I used to call useNavigate() on a certain function upon onClick.

In my Next.js app, I encountered the same issue. In my case, I believe it was a cache-related problem. Running the project after removing the ".next" folder resolved the issue. I hope that removing the build folder in React will have the same effect.

You can convert class component to hooks,but Material v4 has a withStyles HOC. https://material-ui.com/styles/basics/#higher-order-component-api Using this HOC you can keep your code unchanged.

In my case, it was just this single line of code here which was on my App.js that caused this and made me lose 10 hours in debugging. The React Native and Expo could not point me to this. I did everything that was on StackOverflow and github and even the react page that was supposed to solve this and the issue persisted. I had o start taking my code apart bit by bit to get to the culprit

 **const window = useWindowDimensions();**

It was placed like this:

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 ( ....
)}

In my case, I was trying to use mdbreact on windows. Though it installed, But i was getting the above error. I had to reinstall it and everything was ok. It happened to me once two with antd Library

This error can also occur if you're using mobx, and your functional component is wrapped in the mobx observer function. If this is the case, make sure you are using mobx-react version 6.0.0 or higher. Older versions will convert your functional component to a class under the covers and all hooks will fail with this error.

See answer here: React Hooks Mobx: invalid hook call. Hooks can only be called inside of the body of a function component

Here's what fixed it for me. I had the folder node_modules and the files package.json and package-lock.json in my components folder as well as on the root of my project where it belongs. I deleted them from where they don't belong. Don't ask me what I did to put them there, I must have done an npm something from the wrong location.

in my case I removed package-lock.json and node_modules from both projects and re-install again, and now works just fine.


// project structure


root project
- package-lock.json
- package.json // all dependencies are installed here
- node_modules

-- second project
-- package-lock.json
-- package.json 
  "dependencies": {
    "react": "file:../node_modules/react",
    "react-dom": "file:../node_modules/react-dom",
    "react-scripts": "file:../node_modules/react-scripts"
  },
-- node_modules


Not sure what caused the issue in the first place, as this happened to me before and did same steps as above, and issue was resolved.

If you're using react-router-dom, make sure to call useHistory() inside the hook.

You may check your Routes. If you are using render instead of component in Route(<Route path="/testpath" render = {(props)=><Test {...props} />} />) so you properly called your component in an arrow function passing proper props to that.

In my case, the issues was I had cd'd into the wrong directory to do my npm installs. I just re-installed the libraries in the correct directory and it worked fine!

I ran into a similar issue, however my situation was a bit of an edge case.

The accepted answer should work for most people, but for anyone else using react hooks in existing react code that uses Radium, note that hooks won't work without workarounds if you use radium.

In my case, i was exporting my component like so:

// This is pseudocode

const MyComponent = props => {
  const [hookValue, setHookValue] = useState(0);
  return (
    // Use the hook here somehow
  )
}

export default Radium(MyComponent)

Removing that Radium wrapper from the export fixed my issue. If you need to use Radium, resorting to class components and their lifecycle functions may be an easier solution.

Hopefully this helps out at least just one other person.

I ran into this same issue while working on a custom node_module and using npm link for testing within a cra (create react app).

I discovered that in my custom node package, I had to add a peerDependencies

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

After added that into my package.json, I then re-built my custom package. Then in the CRA, I blew away node_modules, re npm install, Re-do the npm link <package>, and then start the project.

Fixed everything!

If your front-end work is in its own folder you might need to install @material-ui/core @material-ui/icons inside that folder, not in the backend folder.

npm i @material-ui/core @material-ui/icons

In my case, I was using navigation in App.js where I have Stack Navigator & assigning all my screens. Please remove below line if you have that.

const navigation = useNavigation()

with NPM npm install react@latest react-dom@latest with YARN yarn add react@latest react-dom@latest

There are many reasons for this to happen. One of which is , when the installation of the packages are done out of scope. It tends to get confused between two react apps.

Explanation:

The packages shouldn't be installed in different levels.

The mistake

app
 |node_modules          <-- some packages installed here
 |package.json
node_modules
package.json            <-- some packages installed here

Correct Way

app
 |node_modules
 |package.json          <-- install all the packages at the same heirarchy

Be aware of import issues- For me the error was about failing imports / auto imports on components and child components. Had nothing to do with Functional classes vs Class components.

  • This is prone to happen as VS code auto importing can specify paths that are not working.
  • if import { MyComponent } is used and export default used in the component the import should say import MyComponent
  • If some Components use index.js inside their folder, as a shotcut for the path, and others not the imports might break. Here again the auto import can cause problems as it merges all components from same folder like this {TextComponent, ButtonComponent, ListComponent} from '../../common'

Try to comment out some components in the file that gives the error and you can test if this is the problem.

本文标签: