首页 > javascript > React如何将新动态密钥添加到现有状态?

React如何将新动态密钥添加到现有状态? (React How to add new dynamic key to existing state?)

问题

我已将数据库中的数据作为数组获取。所以现在我得到这样的数组:

orders:[
{
_id:1,
name: honda,
}
{
_id:2,
name: suzuki,
}
{
_id:3,
name: audi,
}
]

所以我的问题是我如何将新的键值附加到数组,所以它需要如下所示:

orders:[
{
_id:1,
name: honda,
opened:true,
}
{
_id:2,
name: suzuki,
opened:true,
}
{
_id:3,
name: audi,
opened:true,
}
]

现在我正在尝试使用此代码,但这不起作用:

getOrders(orders).then(response => {
        response.map(itm=>{
            const ordersData=[...itm]
            const opened={opened:true}
            this.setState({
                openedOrders: [ordersData,opened]
            })
        })
}) 

openOrders是我创建的新状态对象。什么是最好的解决方案?谢谢

解决方法

假设response包含OP中的第一个数组:

getOrders(orders).then(response => {
  const openedOrders = response.map(order => ({ ...order, open: true}))
  this.setState({ openedOrders } )
})

response.map(order => ({ ...order, open: true})open值添加trueorder数组中的每个键。

问题

I have getting the data from database as an array. So now I'm getting array like this:

orders:[
{
_id:1,
name: honda,
}
{
_id:2,
name: suzuki,
}
{
_id:3,
name: audi,
}
]

So my question is how can I attach new key value to the array, so It needs to look like this:

orders:[
{
_id:1,
name: honda,
opened:true,
}
{
_id:2,
name: suzuki,
opened:true,
}
{
_id:3,
name: audi,
opened:true,
}
]

For now I'm trying with this code, but this doesn't work:

getOrders(orders).then(response => {
        response.map(itm=>{
            const ordersData=[...itm]
            const opened={opened:true}
            this.setState({
                openedOrders: [ordersData,opened]
            })
        })
}) 

openedOrders is new state object that I create. What is best solution for this? Thanks

解决方法

Assuming response contains the first array in your OP:

getOrders(orders).then(response => {
  const openedOrders = response.map(order => ({ ...order, open: true}))
  this.setState({ openedOrders } )
})

response.map(order => ({ ...order, open: true}) adds a key open with the value true to every order in the array.

相似信息