如何用Material UI多选Autocomplete更新React字典状态?
问题修复方案
你的代码存在几个关键问题,导致多选Autocomplete无法正确更新字典状态,以下是修复方案:
核心问题点
- 未定义
employeesList:应使用你声明的associateOptions作为选项数据源 onChange回调参数错误:需传入当前行的row.processPath而非未定义的processPath- 未绑定
value属性:多选组件必须明确绑定对应角色的已选值,才能正确维护状态回显
修复后的完整代码
import { Autocomplete, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, } from '@mui/material'; import { FunctionComponent, useState } from 'react'; const rows = [ { processPath: 'Role 1', headcount: 2 }, { processPath: 'Role 2', headcount: 1 }, { processPath: 'Role 3', headcount: 3 }, { processPath: 'Role 4', headcount: 2 }, { processPath: 'Role 5', headcount: 2 }, ]; export const AccomodationsContent: FunctionComponent = () => { const associateOptions = ['john', 'kevin', 'sally', 'mark']; const [associateList, setAssociateList] = useState<Record<string, string[]>>({}); // 获取对应角色的已选员工,默认返回空数组 const getAssociatesByProcessPath = (processPath: string): string[] => { return associateList[processPath] ?? []; }; const handleSelection = (processPath: string, associates: string[]): void => { setAssociateList((prev) => ({ ...prev, [processPath]: associates, })); }; return ( <> <TableContainer component={Paper} sx={{ minWidth: 800 }}> <Table> <TableHead> <TableRow> <TableCell>Processes</TableCell> <TableCell>Employee Login</TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <TableRow key={row.processPath} 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={`emp-list-${row.processPath}`} options={associateOptions} value={getAssociatesByProcessPath(row.processPath)} renderInput={(params) => ( <TextField {...params} variant='standard' label='Employees' /> )} onChange={(_, values) => handleSelection(row.processPath, values)} /> </TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </> ); };
额外优化说明
- 用
row.processPath替换rowIndex作为TableRow的key,符合React key唯一稳定的最佳实践 - 给每个Autocomplete设置唯一ID(
emp-list-${row.processPath}),避免DOM元素ID重复 - 简化了useState类型定义,因
getAssociatesByProcessPath默认返回空数组,无需保留undefined类型
内容的提问来源于stack exchange,提问作者PandasM
相关产品推荐
相关产品推荐

