每当我try 将makeStyles()用于具有生命周期方法的组件时,我都会遇到以下错误:

无效的钩子调用.钩子只能在函数组件的主体内部调用.发生这种情况的原因如下:

  1. React和渲染器的版本可能不匹配(例如React DOM)
  2. 你可能违反了钩子的规则
  3. 同一个应用程序中可能有多个React副本

下面是产生此错误的代码的一个小示例.其他示例也将类分配给子项.我在MUI的文档中找不到任何显示使用makeStyles的其他方法以及使用生命周期方法的能力的内容.

    import React, { Component } from 'react';
    import { Redirect } from 'react-router-dom';

    import { Container, makeStyles } from '@material-ui/core';

    import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

    const useStyles = makeStyles(theme => ({
      root: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      },
    }));

    const classes = useStyles();

    class Welcome extends Component {
      render() {
        if (this.props.auth.isAuthenticated()) {
          return <Redirect to="/" />;
        }
        return (
          <Container maxWidth={false} className={classes.root}>
            <LogoButtonCard
              buttonText="Enter"
              headerText="Welcome to PlatformX"
              buttonAction={this.props.auth.login}
            />
          </Container>
        );
      }
    }

    export default Welcome;

推荐答案

我们最终停止使用类组件,并从Hooks API for lifecycle methods中创建了功能组件using useEffect().这允许您将makeStyles()与生命周期方法without adding the complication of making Higher-Order Components结合使用.这要简单得多.

例子:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    margin: theme.spacing(1)
  },
  highlight: {
    backgroundColor: 'red',
  }
}));

// Highlight is a bool
const Welcome = ({highlight}) => { 
  const [userName, setUserName] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(true);
  const classes = useStyles();

  useEffect(() => {
    axios.get('example.com/api/username/12')
         .then(res => setUserName(res.userName));
  }, []);

  if (!isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
      <LogoButtonCard
        buttonText="Enter"
        headerText={isAuthenticated && `Welcome, ${userName}`}
        buttonAction={login}
      />
   </Container>
   );
  }
}

export default Welcome;

Reactjs相关问答推荐

React路由子路由将其重定向到带有参数的错误URL

为什么我无法访问窗口事件处理程序中的状态?

为什么这个'Suspense'子组件在挂起promise解决后会丢失它的状态,而不是呈现?<>

一键MUI导出

如何通过回调函数获取多个值?

React,当我调用handleSubmit()函数时,我正在将application/json和multiform/data中的数据发送到后端,但student_image中没有数据:null

在React中使用映射创建flex组件

如何在中间件中获取 nextAuth 会话

面临 React 模式中点击外部条件的问题

设置自定义形状的纹理

我可以同时使用 Gatsby 和 NEXT.JS 吗?

React:如何使用条件渲染和react 挂钩来更新另一个组件的状态?

类型错误:类型typeof import(js-cookie)上不存在属性get

Cypress 组件测试不渲染react 组件(但它的内容)

如何在 React 中使用 debounce hooks

React CSSTransition 两次创建新页面并在这两个相同的页面上运行转换

在表格中显示具有自定义声明的用户状态

将 dict 值转换并插入到react 钩子的列表中

在视图列表上react 本机无限循环的反弹动画?

找不到元素 - 这是参考问题吗?