You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Antd Menu组件触发Maximum update depth exceeded报错求助

解决Ant Design Menu组件移动端点击导航报错问题

问题分析

你的报错核心原因是移动端渲染时Menu Item的DOM结构与桌面端存在差异,导致onSelect事件中e.item.props.location无法正确获取值,进而触发报错。同时你对selectedKey的处理存在冗余,可能引发状态不同步问题。

修复步骤

1. 修正导航逻辑,避免直接访问Item内部props

不要依赖e.item.props获取自定义字段,改用e.key匹配对应的路由地址,这是跨端可靠的方式:

function onSelect(e){
  const targetItem = items.find(item => item.key === e.key);
  if(targetItem){
    navigate(targetItem.location);
  }
}

2. 简化选中状态计算,移除冗余状态

selectedKey完全由location.pathname决定,无需用useState存储,直接在渲染时推导即可,避免状态同步问题:

// 移除原有的useState、useCallback、useEffect相关代码
const selectedKey = location.pathname === "/" ? "list" : "add";

同时移除defaultSelectedKeys,因为selectedKeys处于受控模式,默认值不再生效:

<Menu 
  onSelect={onSelect} 
  mode="horizontal" 
  items={items} 
  selectedKeys={[selectedKey]}
/>

3. 完整修正后的代码

import React from 'react';
import { UnorderedListOutlined, DiffOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from "react-router-dom";
import { Menu } from 'antd';

export function Menus(){
  const navigate = useNavigate();
  const location = useLocation();

  const selectedKey = location.pathname === "/" ? "list" : "add";

  function onSelect(e){
    const targetItem = items.find(item => item.key === e.key);
    if(targetItem){
      navigate(targetItem.location);
    }
  }

  const items = [
    {
      key: "list",
      icon: <UnorderedListOutlined />,
      label: "Liste des todos",
      location: "/"
    },
    {
      key: "add",
      icon: <DiffOutlined />,
      label: "Ajouter une todo",
      location: "/add"
    }
  ];

  return (
    <Menu 
      onSelect={onSelect} 
      mode="horizontal" 
      items={items} 
      selectedKeys={[selectedKey]}
    />
  )
}

export default Menus;

额外说明

  • Ant Design Menu的onSelect事件参数中,e.key是跨端可靠的标识,优先用它关联自定义数据,而非直接访问DOM元素的props。
  • 当状态可通过props/上下文直接推导时,不要额外用useState存储,减少状态同步风险。

内容的提问来源于stack exchange,提问作者Boris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:45:36