使用 useState 解构对象
Destructuring an object with useState
我收到这个错误:
Unhandled Rejection (TypeError): object is not iterable (cannot read property Symbol(Symbol.iterator))
解构时...setVaults 内的保险库(对象)。
代码:
const [vaults, setVaults] = useState();
const name = 'something'
const totalSupply = 155000
const totalBorrowed = 55050
const capUtilRate = 0
setVaults(...vaults, {[name]: {totalSupply, totalBorrowed, capUtilRate}})
为什么会这样?
初始状态未定义,因此不可迭代。看来你的状态是一个对象。您还应该使用功能状态更新。删除您尝试设置的 属性 周围的大括号。
const [vaults, setVaults] = useState({});
...
const name = 'something';
const totalSupply = 155000;
const totalBorrowed = 55050;
const capUtilRate = 0;
setVaults(vaults => ({
...vaults, // <-- spread previous state
[name]: { // <-- create new object reference
totalSupply,
totalBorrowed,
capUtilRate,
},
}));
我收到这个错误:
Unhandled Rejection (TypeError): object is not iterable (cannot read property Symbol(Symbol.iterator))
解构时...setVaults 内的保险库(对象)。
代码:
const [vaults, setVaults] = useState();
const name = 'something'
const totalSupply = 155000
const totalBorrowed = 55050
const capUtilRate = 0
setVaults(...vaults, {[name]: {totalSupply, totalBorrowed, capUtilRate}})
为什么会这样?
初始状态未定义,因此不可迭代。看来你的状态是一个对象。您还应该使用功能状态更新。删除您尝试设置的 属性 周围的大括号。
const [vaults, setVaults] = useState({});
...
const name = 'something';
const totalSupply = 155000;
const totalBorrowed = 55050;
const capUtilRate = 0;
setVaults(vaults => ({
...vaults, // <-- spread previous state
[name]: { // <-- create new object reference
totalSupply,
totalBorrowed,
capUtilRate,
},
}));