P粉8248896502023-08-15 09:10:52
"Error: Rendering with more hooks than the last render" usually occurs when you use React hooks (such as useSelector) in a way that violates the hooks rules. The rules state that hooks must always be called at the top level of a functional component, and not within loops, conditionals, or nested functions. In your code, you seem to be using the CheckPermission function in a loop and conditional.
// Sidebar.js import React from "react"; import { useSelector } from "react-redux"; import { NavLink, Tooltip } from "your-react-ui-library"; // 导入您的UI库 const Sidebar = ({ collapse, onCollapse, isAdmin, menus }) => { const { user } = useSelector((state) => ({ user: state.auth.user, })); // 将权限检查逻辑直接移入Sidebar组件 const checkPermission = (module_key, permission_key) => { const rolePermissions = user?.role?.role_permissions ?? []; return !!rolePermissions.find( (p_list) => p_list.module?.key === module_key && p_list.permission?.key === permission_key ); }; const renderMenu = (menu, key) => { // 使用本地的checkPermission函数进行权限检查 if ( !checkPermission(menu.moduleKey, menu.permissionKey) || (!isAdmin && !menu.path) ) { return null; } return ( <Tooltip title={menu.name} placement="right" key={key}> <NavLink activeClassName={styles.active} exact className={styles.item} to={menu.path} > <span className={styles.iconBox}>{menu.icon}</span> <span className={styles.itemText}> {menu.name}</span> </NavLink> </Tooltip> ); }; return ( <Layout.Sider // ... 其他属性和样式 ... > <div className={styles.action}> {user && user.read_only ? menus.map((menu, i) => { if (menu.name === "Харилцагч") { return renderMenu(menu, i); } else { return ( menu && menu.children && // eslint-disable-next-line array-callback-return menu.children.map((submenu, j) => { if (submenu.name === "QR данс") { return ( <div key={i} className={styles.parentnav}> {renderMenu(submenu, j)} </div> ); } }) ); } }) : menus.map((menu, i) => { if (menu.path) { return renderMenu(menu, i); } else { return ( <div key={i} className={styles.parentnav}> {menu.name ? ( <div className={`${styles.navlabel} ${styles.partentText}`} > {menu.name} </div> ) : null} {menu.children.map((submenu, j) => { if (!submenu.path) return null; if (isAdmin) { return renderMenu(submenu, j); } else { return null; } })} </div> ); } })} </div> </Layout.Sider> ); }; export default Sidebar;