P粉7148900532023-08-16 09:07:01
When you create an object using curly braces like { id: tableState }, the string "id" is interpreted as a static key instead of the dynamic value of the id variable. You need to use computed property names in JavaScript/TypeScript. Computed property names allow you to use dynamic values as keys when creating objects.
// App.tsx--------------------------------------- React.useEffect(() => { setCallback((id: TableId, tableState: TableState) => { const map: Record<TableId, TableState> = { [id]: tableState }; // 在这里使用计算属性名 setTableStateMap(map); }); // Table Component------------------------------- // ... your other imports and code export const Table: React.FC<TableProps> = ({ id, }) => { let tableState: TableState | undefined; if (id) { tableState = stateMap[id]; // 现在这将正确地使用动态 id 访问值 } else { tableState = undefined; } // ... rest of your component code };