在 Typescript 中使用变量名作为键而不是变量值来记录对象

问题描述 投票:0回答:1

我正在尝试使用

Record<TableId, TableState>
对象,其中
type TableId = string;
。但是,当我通过
setTableStateMap(map)
设置键/值对后去打印记录对象的内容时...我得到的是对象
{id: {…}}
,而不是我传递给“id”变量的值。

// App.tsx---------------------------------------
React.useEffect(() => {
    setCallback((id: TableId, tableState: TableState) => {
        const map: Record<TableId, TableState> = { id: tableState };
        setTableStateMap(map);
    });
    

// Table Component-------------------------------
type TableId = string;
type Callback = (id: TableId, state: TableState) => void;
let callback: Callback;
export function setCallback(callbackInput: Callback) {
    callback = callbackInput;
}

let stateMap: Record<TableId, TableState> = {};
export function setTableStateMap(map: Record<TableId, TableState>) {
    stateMap = map;
}

interface TableProps {
    id?: TableId;
}

export const Table: React.FC<TableProps> = ({
    id,
}) => {

    let tableState: TableState | undefined;
    if (id) {
        tableState = stateMap[id];
        // stateMap has key set to 'id' and not value of variable id
        // {id: {…}}
    } else {
        tableState = undefined;
    }
};
javascript reactjs typescript callback record
1个回答
0
投票

当您使用花括号和像 { id: tableState } 这样的键创建对象时,字符串“id”将被解释为静态键,而不是 id 变量的动态值。您需要在JavaScript/TypeScript。计算属性名称允许您在创建对象时使用动态值作为键。

// App.tsx---------------------------------------
React.useEffect(() => {
    setCallback((id: TableId, tableState: TableState) => {
        const map: Record<TableId, TableState> = { [id]: tableState }; // Use computed property name here
        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]; // Now this will correctly access the value using the dynamic id
    } else {
        tableState = undefined;
    }
// ... rest of your component code
};
© www.soinside.com 2019 - 2024. All rights reserved.