【发布时间】:2021-10-31 23:30:43
【问题描述】:
我正在开发一个反应应用程序,我必须更改数组中对象的键。这是我的代码:
getInterfaces(){
//assign a array to interfaceOption state
let interfaceOptions=[
{
"interface_name": "ORU",
"interface_id": "1"
},
{
"interface_name": "MLM",
"interface_id": "2"
},
]
//change interfaceOptions keys to title and value
let interfaceOptionsWithTitle = interfaceOptions.map(function(item){
return {
title: item.interface_name,
value: item.interface_id
}
})
console.log(interfaceOptionsWithTitle)
this.setState({
interfaceOptions: interfaceOptionsWithTitle
})
//print updated interfaceOptions
console.log(this.state.interfaceOptions)
}
这里我最初分配了一个数组,然后我更改了它的键并使用 console.log 打印它并打印更新的数组但是当我再次 setState 数组和控制台记录它时,它返回一个空数组。有人可以帮忙我明白这个吗?
如果我想更新 interfaceOptions,这会起作用吗?
this.state.interfaceOptions = this.state.interfaceOptions.map(item => {
return {
title: item.interface_name,
value: item.interface_id
};
});
谢谢
【问题讨论】:
-
请查看answer
-
setState 是一个异步函数,使用回调来打印我们放在 getInterfaces 之外的 console.log
标签: javascript arrays reactjs react-hooks setstate