reactjs - 如何防止react-router-dom Link组件重新渲染?

标签 reactjs react-router-dom

我试图限制每次用户单击某些内容时在我的应用程序上重新渲染的组件数量。鉴于无论用户位于哪个页面,侧边栏都会呈现,因此将其包装在 React.memo 中似乎是有意义的。功能。这效果很好,侧边栏组件本身似乎没有重新渲染。然而,<Link>元素,我从 react-router-dom 导入重新渲染,就像SidebarAuthButtons一样和 SidebarCreateButton .

我可以采取什么措施来防止这种行为?

import React, { memo } from "react";
import { Link } from "react-router-dom";
import {
  SidebarContainer,
  SidebarLogo,
  SidebarNav,
  SidebarMenu,
  SidebarListItem,
  SidebarButton,
} from "../styles/SidebarStyles";

function Sidebar({ auth }) {
  const SidebarAuthButtons = (
    <div>
      <SidebarButton>
        <Link to="/login">Log In</Link>
      </SidebarButton>
      <SidebarButton outlined={true}>
        <Link to="/register">Create Account</Link>
      </SidebarButton>
    </div>
  );

  const SidebarCreateButton = (
    <SidebarButton>
      <Link to="#">Create</Link>
    </SidebarButton>
  );

  return (
    <SidebarContainer>
      <SidebarLogo>React Project</SidebarLogo>
      <SidebarNav>
        <SidebarMenu>
          <SidebarListItem isHeading={true}>Menu</SidebarListItem>
          <SidebarListItem>
            <Link to="/">Explore</Link>
          </SidebarListItem>
          <SidebarListItem>
            <Link to="/blogs">Blogs</Link>
          </SidebarListItem>
          <SidebarListItem>
            <Link to="/podcasts">Podcasts</Link>
          </SidebarListItem>
          <SidebarListItem>
            <Link to="/youtube">Youtube</Link>
          </SidebarListItem>
        </SidebarMenu>
        {auth.isAuthenticated ? SidebarCreateButton : SidebarAuthButtons}
      </SidebarNav>
    </SidebarContainer>
  );
}

export default memo(Sidebar);

最佳答案

SidebarAuthButtonsSidebarCreateButton 移到功能组件渲染范围之外,使它们成为 React 组件(目前它们只是保存到变量中的 jsx)。这应该可以修复重新渲染问题。

关于reactjs - 如何防止react-router-dom Link组件重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61424031/

相关文章:

css - 如何让我的元素占据屏幕宽度的 100%,即使它位于占据屏幕 80% 的元素内?

javascript - 如何以正确的顺序显示月份?

css - react Bootstrap 表未对齐的标题列

reactjs - React Renders 在我的组件的底部!没有顶部

reactjs - React-router-dom History.goBack() 在 Firefox 和 Safari 上不起作用

javascript - react 路由器 - 无法传递存储

css - 自定义 semantic-ui-react (npm)

javascript - 使用模块化 CSS 在 React 中使用状态字符串作为类名

javascript - 如何在每个路由中渲染相同的组件

javascript - React Router with - Ant Design Sider : how to populate content section with components for relevant menu item