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

MUI Autocomplete组件选择数量限制问题排查

问题解决:Autocomplete组件报错"Cannot read properties of undefined (selectedHeadcount)"

你遇到的错误核心是访问associateList数据的方式错误——associateList是以processPath为键的字典,不能直接用.processPath访问,必须通过当前循环行的row.processPath作为键来获取对应数据。另外,硬编码的3应该替换为每行实际的headcount值,才能匹配数据库返回的数量限制。

以下是修复后的完整代码:

const rows = [
  { processPath: 'role1', headcount: 2 },
  { processPath: 'role2', headcount: 3 },
  { processPath: 'role3', headcount: 2 },
  { processPath: 'role4', headcount: 2 },
  { processPath: 'role5', headcount: 1 },
];

type EmployeesDictionary = Record<string, Record<string, string[] | number>>;

export const CriticalRolesContent: FunctionComponent = () => {
  const employeesList = ['john', 'sally', 'mark', 'kevin']
  // 注:原代码中disableOptimizerButton未定义,若需使用请补充定义

  const newDictionary: EmployeesDictionary = {};

  rows.forEach((row) => {
    newDictionary[row.processPath] = {
      associates: [],
      selectedHeadcount: 0,
    };
  });

  const [associateList, setAssociateList] = useState<EmployeesDictionary>(newDictionary);

  const handleSelection = (processPath: string, associates: string[], reason: string, detail: any): void => {
    setAssociateList((prevAssociateList) => ({
      ...prevAssociateList,
      [processPath]: { associates: associates, selectedHeadcount: associates.length },
    }));
  };

  return (
    <>
      <TableContainer>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Process Path</TableCell>
              <TableCell>Associate Login</TableCell>
              <TableCell>Headcount Allowed</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {rows.map((row, rowIndex) => {
              // 提前获取当前角色的已选数据
              const currentSelection = associateList[row.processPath];
              return (
                <TableRow
                  key={rowIndex}
                  sx={{
                    '&:last-child td, &:last-child th': { border: 0 },
                  }}>
                  <TableCell style={{ width: '35%' }}>{row.processPath}</TableCell>
                  <TableCell style={{ width: '45%' }} component='th' scope='row'>
                    <Autocomplete
                      multiple
                      id={`employee-list-${row.processPath}`} {/* 给每个组件设置唯一ID */}
                      options={employeesList}
                      limitTags={row.headcount} {/* 标签数量匹配人数上限 */}
                      getOptionLabel={(option) => option} {/* 字符串数组直接返回自身 */}
                      getOptionDisabled={() => currentSelection.selectedHeadcount >= row.headcount}
                      disableCloseOnSelect={currentSelection.selectedHeadcount >= row.headcount}
                      value={currentSelection.associates} {/* 绑定已选人员列表,确保状态同步 */}
                      renderInput={(params) => <TextField {...params} variant='standard' label='Select Employees' />}
                      onChange={(event, list, reason, detail) => handleSelection(row.processPath, list, reason, detail)}
                    />
                  </TableCell>
                  <TableCell>{row.headcount}</TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </>
  );
};

核心修改说明:

  • 修正数据访问逻辑:用associateList[row.processPath]替代错误的associateList.processPath,正确获取当前角色的已选数据
  • 替换硬编码值:将固定的3改为row.headcount,匹配每行的实际人数限制
  • 添加状态绑定:给Autocomplete增加value={currentSelection.associates},确保组件显示与本地state同步
  • 唯一ID设置:为每个Autocomplete生成唯一ID,避免DOM元素冲突
  • 简化代码逻辑:在循环内提前获取currentSelection,减少重复数据访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 10:11:14