Home  >  Q&A  >  body text

Why use variable names as keys in object properties instead of variable values?

<p>I'm trying to use a <code>Record<TableId, TableState></code> object where <code>type TableId = string;</code>. However, when I print the contents of the record object after setting the key/value pairs via <code>setTableStateMap(map)</code>... what I get is the object <code>{id: {…}} </code> instead of the value I passed to the 'id' variable. </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]; // The key of stateMap is set to 'id', not the value of the variable id // {id: {…}} } else { tableState = undefined; } };</pre> <p><br /></p>
P粉129168206P粉129168206455 days ago452

reply all(1)I'll reply

  • P粉714890053

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

    reply
    0
  • Cancelreply