首頁  >  問答  >  主體

為何在物件屬性中使用變數名稱作為鍵,而不是變數值?

<p>我正在嘗試使用一個<code>Record<TableId, TableState></code>對象,其中<code>type TableId = string;</code>。然而,當我在透過<code>setTableStateMap(map)</code>設定鍵/值對之後列印記錄物件的內容時...我得到的是物件<code>{id: {…}} </code>,而不是我傳遞給'id'變數的值。 </p> <pre class="brush:php;toolbar:false;">// 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的鍵設定為'id',而不是變數id的值 // {id: {…}} } else { tableState = undefined; } };</pre> <p><br /></p>
P粉129168206P粉129168206406 天前417

全部回覆(1)我來回復

  • P粉714890053

    P粉7148900532023-08-16 09:07:01

    當你使用類似 { id: tableState } 的大括號來建立物件時,字串 "id" 被解釋為靜態鍵,而不是 id 變數的動態值。你需要在 JavaScript/TypeScript 中使用計算屬性名稱。計算屬性名稱允許你在建立物件時使用動態值作為鍵。

    // 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
    };
    

    回覆
    0
  • 取消回覆