【问题标题】:update state of an object in react-native - I am not using redux在 react-native 中更新对象的状态 - 我没有使用 redux
【发布时间】:2025-12-26 03:05:06
【问题描述】:

我有一个类似的构造函数

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 会是这样的

  next_item_key = 'qwerty'
  next_item_value = 'pqrs'

我的结果 item_details 应该看起来像

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

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

【问题讨论】:

    标签: javascript reactjs object react-native setstate


    【解决方案1】:

    你可以使用扩展操作符来保持你之前的状态:

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

    【讨论】:

    • 最好使用带有prevState 的回调来保证正确的状态更改。
    【解决方案2】:

    使用[] notationspread operator 来实现。

    这样写:

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

    更新:

    在循环中调用 setState 不是一个好主意,更好的方法是先进行所有计算,然后在拍摄时更新状态值。

    像这样:

    let data = {};
    response.result.variants.forEach((element) => {
        data[element.title]: false;
    });
    
    this.setState(prevState => ({in_wishlist: { ...prevState.in_wishlist, ...data }}))
    

    【讨论】:

    【解决方案3】:

    Object.assign 应该满足您的需求:

    const newState = Object.assign(this.state.item_details, {[next_item_key]: next_item_value})

    或者使用扩展运算符:

    const newState = {...this.state.itemDetails, [next_item_key]: next_item_value}

    【讨论】: