首页 > 解决方案 > 如何向从 fetch 获取的 json 添加另一个属性?

问题描述

我有以下代码:

useEffect(() => {
    listAccountsWorker()
        .then(res => {
            for (account of res) {
                // Account is not defined
                account.isSelected = false;
            }
            setAccounts(accounts)
        })
        .catch(error => {
            if (error.status === 401) {
                history.push('/login');
            }
        });
}, []);

我想向数组中的对象添加一个新属性,isSelected但是出现错误'account' is not defined。Worker 使用JSfetch 并在 promise 中返回结果,其内容res是一个对象数组,例如[{ label: 'hello', ...}, { label: 'bye', ...}]. 我在这里做错了什么?

标签: javascriptfetch-api

解决方案



useEffect(() => {
    listAccountsWorker()
        .then(res => {
            // defined `account`
            for (const account of res) {
                account.isSelected = false;
            }
            setAccounts(accounts)
        })
        .catch(error => {
            if (error.status === 401) {
                history.push('/login');
            }
        });
}, []);

推荐阅读