与MUI的useStyles()反应,给我一个违反钩子的规则

时间:2020-06-14 00:31:48

标签: reactjs material-ui

我遇到了可怕的React“ Invalid Hook Call”错误,并且我没有运行任何钩子。

  1. 使用CRA安装React
  2. 已安装的MUI
  3. 构建简单样式页面:
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
  root: {
    display: 'flex',
    justifyContent: 'center',
  },
  layout: {
    minHeight: '230px',
  },
}));

export default useStyles;
  1. 为组件添加了样式:
import React from 'react';
import useStyles from './styles';
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';

const SimpleComponent = (props) => {
  const classes = useStyles();
  return (
    <React.Fragment>
      <Container className={classes.root}>
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <div>Page Content</div>;
          </Grid>
        </Grid>
      </Container>
    </React.Fragment>
  );
};

export default SimpleComponent;

应用程序在npm start上未返回任何错误,但是页面本身给了我指向行const classes = useStyles();的无效钩子调用。那不是一个钩子。

我尝试重新npm install应用程序,无论如何我都得到相同的页面,我一直尝试移动呼叫。似乎很多人在此配置上都遇到了类似的问题,但是没有其他解决方案可以解决我的问题。

挂钩错误页面:

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[https://reactjs.org/warnings/invalid-hook-call-warning.html][1] for tips about how to debug and fix this problem.

SimpleComponent
src/Components/PaymentHistory/PaymentHistory.js:7
   4 | import Container from '@material-ui/core/Container';
   5 | 
   6 | const SimpleComponent = (props) => {
>  7 |   const classes = useStyles();
   8 |   return (
   9 |     <React.Fragment>
  10 |       <Container className={classes.root}>
View compiled  

1 个答案:

答案 0 :(得分:2)

请确保正确安装了所有依赖项(包括@ material-ui / core)。

这里是工作中的demo

相关问题