为何在对象属性中使用变量名作为键,而不是变量值?
P粉129168206
P粉129168206 2023-08-15 14:11:32
[JavaScript讨论组]
<p>我正在尝试使用一个<code>Record&lt;TableId, TableState&gt;</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(() =&gt; { setCallback((id: TableId, tableState: TableState) =&gt; { const map: Record&lt;TableId, TableState&gt; = { id: tableState }; setTableStateMap(map); }); // Table Component------------------------------- type TableId = string; type Callback = (id: TableId, state: TableState) =&gt; void; let callback: Callback; export function setCallback(callbackInput: Callback) { callback = callbackInput; } let stateMap: Record&lt;TableId, TableState&gt; = {}; export function setTableStateMap(map: Record&lt;TableId, TableState&gt;) { stateMap = map; } interface TableProps { id?: TableId; } export const Table: React.FC&lt;TableProps&gt; = ({ id, }) =&gt; { let tableState: TableState | undefined; if (id) { tableState = stateMap[id]; // stateMap的键设置为'id',而不是变量id的值 // {id: {…}} } else { tableState = undefined; } };</pre> <p><br /></p>
P粉129168206
P粉129168206

全部回复(1)
P粉714890053

当你使用带有类似 { 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
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号