【问题标题】:React Sidebar menu items do not update active state unless i refresh除非我刷新,否则 React 侧边栏菜单项不会更新活动状态
【发布时间】:2021-12-13 05:37:18
【问题描述】:

我在我的 react 应用程序中将 react-sidebar-pro 用于我的侧边栏组件,我希望当用户单击并重定向到链接时,我的侧边栏菜单项的活动状态变为 true。到目前为止,我所做的是设置一个参数,如果用户位于特定地址,它将变为 true,但它仅在我刷新页面时更新。如何在不刷新页面的情况下更新它,使其看起来响应?我想过使用 useState 来解决这个问题,但我不知道如何将它应用到代码中,因为我还在学习 React

这是我的 Sidebar.js

function Sidebar() {
        //create initial menuCollapse state using useState hook
        const [menuCollapse, setMenuCollapse] = useState(false)

        //create a custom function that will change menucollapse state from false to true and true to false
      const menuIconClick = () => {
        //condition checking to change state from true to false and vice versa
        menuCollapse ? setMenuCollapse(false) : setMenuCollapse(true);
      }
    return (
        <>
        <div id="header">
            {/* collapsed props to change menu size using menucollapse state */}
          <ProSidebar collapsed={menuCollapse}>
            <SidebarHeader>
            <div className="logotext">
                {/* small and big change using menucollapse state */}
                <p>{menuCollapse ? "LOGO" : "LONG LOGO"}</p>
              </div>
              <div className="closemenu" onClick={menuIconClick}>
                  {/* changing menu collapse icon on click */}
                {menuCollapse ? (
                  <FiArrowRightCircle/>
                ) : (
                  <FiArrowLeftCircle/>
                )}
              </div>
            </SidebarHeader>
            <SidebarContent>
              <Menu iconShape="square">
                <MenuItem active={window.location.pathname === "/"} icon={<FiHome />} >
                  Home
                <Link to="/"/>
                </MenuItem>
                <MenuItem  active={window.location.pathname === "/FAQ"}  icon={<FaList />}>
                  FAQ 
                <Link to="/FAQ"/>
                </MenuItem>
                <MenuItem  active={window.location.pathname === "/Search-sec"} icon={<RiPencilLine />}>SEARCH SEC<Link to="/Search-sec"/></MenuItem>
            </SidebarContent>
            <SidebarFooter>
              <Menu iconShape="square">
                <MenuItem icon={<FiLogOut />}>Logout</MenuItem>
              </Menu>
            </SidebarFooter>
          </ProSidebar>
        </div>
      </>
    )
}

export default Sidebar

【问题讨论】:

  • 因为 react 组件不知道 window.location 更改,因为 window.location 不是 prop 或本地状态。因此,组件不会重新渲染。

标签: javascript reactjs react-native react-hooks react-router


【解决方案1】:

这里基本上有两种选择:

  1. 将 window.location.path 设为本地状态 请参考Why useEffect doesn't run on window.location.pathname changes?
  2. 添加另一个状态(根据点击改变),强制组件重新渲染

function Sidebar() {

  const [menuCollapse, setMenuCollapse] = useState(false);
  const [activeIndex, setActiveIndex] = useState(() => { 
    const initialIndex = 
      window.location.pathname === '/' ? 0 
      : window.location.pathname === '/FAQ' ? 1 
        : window.location. pathname === 'Search-sec' ? 2 
          : 0; 
    return initialIndex; 
  });

  const menuIconClick = () => {
    setMenuCollapse(!menuCollapse);
  };

  return (
    <>
      <div id="header">
        {/* collapsed props to change menu size using menucollapse state */}
        <ProSidebar collapsed={menuCollapse}>
          <SidebarHeader>
            <div className="logotext">
              {/* small and big change using menucollapse state */}
              <p>{menuCollapse ? "LOGO" : "LONG LOGO"}</p>
            </div>
            <div className="closemenu" onClick={menuIconClick}>
              {/* changing menu collapse icon on click */}
              {menuCollapse ? (
                <FiArrowRightCircle />
              ) : (
                <FiArrowLeftCircle />
              )}
            </div>
          </SidebarHeader>
          <SidebarContent>
            <Menu iconShape="square">
              <MenuItem active={activeIndex === 0} icon={<FiHome />} >
                Home
                <Link id="MenuItemHome" to="/" onClick={() => setActiveIndex(0)} />
              </MenuItem>
              <MenuItem  active={activeIndex === 1}  icon={<FaList />} >
                FAQ
                <Link id="MenuItemFAQ" to="/FAQ" onClick={() => setActiveIndex(1)} / >
              </MenuItem>
              <MenuItem  active={activeIndex === 2} icon={<RiPencilLine />}>
                SEARCH SEC
                <Link id="MenuItemSearch" to="/Search-sec" onClick={() => setActiveIndex(2)} />
              </MenuItem>
            </Menu>
          </SidebarContent>
          <SidebarFooter>
            <Menu iconShape="square">
              <MenuItem icon={<FiLogOut />}>Logout</MenuItem>
            </Menu>
          </SidebarFooter>
        </ProSidebar>
      </div>
    </>
  );
}

export default Sidebar;

【讨论】:

  • 非常感谢。效果很好。我真的很迷茫,因为我不确定如何在我的代码中为该部分应用 useState。但是,如果我希望 MenuItem 的活动状态在我根据 url 刷新时保持不变,我应该参考第一个选项吗?
  • 啊,我明白了,您说的是使用状态的动态初始值。因此,根据您的要求,您可能希望将代码 const [activeIndex, setActiveIndex] = useState(0); 更改为 const [activeIndex, setActiveIndex] = useState(() =&gt; { const initialIndex.= window.location. pathname === '/' ? 0 : window.location. pathname === '/FAQ ? 1 : window.location. pathname === 'Search-sec ? 2 : 0; return initialIndex; });
  • 我已经更新了答案,参考对第二个useState所做的更改
猜你喜欢
  • 2020-07-16
  • 2021-05-14
  • 1970-01-01
  • 2022-07-19
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 2018-02-11
  • 1970-01-01
相关资源
最近更新 更多