gpt4 book ai didi

javascript - 在 react-native 中更新对象的状态 - 我没有使用 redux

转载 作者:行者123 更新时间:2023-11-29 21:01:47 25 4
gpt4 key购买 nike

我有一个像这样的构造函数

constructor() {
this.state = {
item_details : {}
}
}

someFunc(next_item_key,next_item_value) {
//append this next_item_key , next_item_value pair to item_detials
}

我需要将 someFunc 中的这个 next_item 添加到我的状态变量 item_details..

例子: 我的 item_details 看起来像这样

   item_details : {'abc' : 'xyz' , 'a12' : '123' }

我的下一个项目会是这样的

  next_item_key = 'qwerty'
next_item_value = 'pqrs'

我的结果 item_details 应该是这样的

 item_details : {'abc' : 'xyz' , 'a12' : '123' , 'qwerty' : 'pqrs' }

我应该在 someFunc 中写什么才能得到这个结果

最佳答案

您可以使用扩展运算符来保持您之前的状态:

this.setState(prevState => ({ item_details:
{
...prevState.item_details,
[next_item_key]: next_item_value
}
}));

关于javascript - 在 react-native 中更新对象的状态 - 我没有使用 redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46095033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com