首页 > 解决方案 > 使用 MUI 和样式化组件重新渲染的次数过多

问题描述

您好我尝试渲染一个使用 MUI(Material-UI) 和 styled-component 的页面。我已经使用主题和 useMediaQuery 让我的 web 应用程序响应。如果它是一个小型设备,我试图让我的应用程序响应并更改字体大小

我的问题是根据控制台渲染太多

我知道问题在于 useState 的 if else 语句,但我不知道还有什么其他选择可以使这成为可能

这是以下代码:

import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Button from '@material-ui/core/Button';
import { Link } from 'react-router-dom';
import Logojsam from '../../assets/icons/logo-jsam.png';

import useMediaQuery from '@material-ui/core/useMediaQuery';
import { useTheme } from '@material-ui/core/styles';

import styled from 'styled-components';
const useStyles = makeStyles((theme) => ({
  rightToolbar: {
    marginLeft: 'auto',
    marginRight: -10,
  },
  logo: {
    width: 185,
    height: 185,
    padding: '20px 0px',
  },
}));

const MyButton = styled(Button)({
  padding: '0 14px',
  fontSize: (props) => props.fontSize || '20px',
});



const Navbar = () => {
  const classes = useStyles();
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'));
  const isMedium = useMediaQuery(theme.breakpoints.down('md'));

  const [fontSize, setfontSize] = useState();
 
  if (isMedium)
  {
    setfontSize('45px');
  }
    return (
      <div>
        <AppBar
          position="static"
          elevation={0}
          style={{
            background: 'white',
          }}
        >
          <Toolbar>
            <img className={classes.logo} src={Logojsam} alt="Bosch Logo" />
            {!isMobile && (
              <section className={classes.rightToolbar}>
                <MyButton fontSize={fontSize} component={Link} to="/">
                  About Us
                </MyButton>
                <MyButton component={Link} to="/community">
                  Community
                </MyButton>
                <MyButton component={Link} to="/community">
                  Activities
                </MyButton>
                <MyButton component={Link} to="/gallery">
                  Gallery
                </MyButton>
                <MyButton component={Link} to="/contact-us">
                  Contact Us
                </MyButton>
                <MyButton component={Link} to="/contact-us">
                  En
                </MyButton>
              </section>
            )}
          </Toolbar>
        </AppBar>
      </div>
    );
};

export default Navbar;



谢谢

标签: javascriptreactjsreact-hooksmaterial-uistyled-components

解决方案


useEffect()Hook 允许您在函数组件中执行副作用。如评论中所述。通过 Jayce444,当您setfontSize()在组件的主体内部调用时,它会触发重新渲染。isMedium将其放入 useEffect 中,仅在更改时重新运行

import React, { useState, useEffect } from 'react';

然后

useEffect(() => {
  if (isMedium){
    setfontSize('45px')
  }
}, [isMedium]); // Only re-run the effect if isMedium changes

推荐阅读