在React中使用setState更新对象

在React中使用setState更新对象

本文介绍了在React中使用setState更新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用setState更新对象的属性?

Is it at all possible to update object's properties with setState?

类似的东西:

this.state = {
   jasper: { name: 'jasper', age: 28 },
}

我尝试过:

this.setState({jasper.name: 'someOtherName'});

和这个:

this.setState({jasper: {name: 'someothername'}})

第一个导致语法错误,第二个则什么都不做.有什么想法吗?

The first results in a syntax error and the second just does nothing. Any ideas?

推荐答案

这样做的方法有多种,因为状态更新是,因此要更新状态对象,我们需要使用更新程序功能setState.

There are multiple ways of doing this, since state update is a async operation, so to update the state object, we need to use updater function with setState.

1-最简单的一个:

首先创建jasper的副本,然后在其中进行更改:

First create a copy of jasper then do the changes in that:

this.setState(prevState => {
  let jasper = Object.assign({}, prevState.jasper);  // creating copy of state variable jasper
  jasper.name = 'someothername';                     // update the name property, assign a new value
  return { jasper };                                 // return new object jasper object
})

我们也可以这样写,而不是使用Object.assign:

Instead of using Object.assign we can also write it like this:

let jasper = { ...prevState.jasper };

2-使用传播算子 :

this.setState(prevState => ({
    jasper: {                   // object that we want to update
        ...prevState.jasper,    // keep all other key-value pairs
        name: 'something'       // update the value of specific key
    }
}))

注意::Object.assignSpread Operator仅创建,因此,如果您定义了嵌套对象或对象数组,则需要另一种方法.

Note: Object.assign and Spread Operator creates only shallow copy, so if you have defined nested object or array of objects, you need a different approach.

假设您将状态定义为:

this.state = {
  food: {
    sandwich: {
      capsicum: true,
      crackers: true,
      mayonnaise: true
    },
    pizza: {
      jalapeno: true,
      extraCheese: false
    }
  }
}

要更新披萨对象的ExtraCheese:

To update extraCheese of pizza object:

this.setState(prevState => ({
  food: {
    ...prevState.food,           // copy all other key-value pairs of food object
    pizza: {                     // specific object of food object
      ...prevState.food.pizza,   // copy all pizza key-value pairs
      extraCheese: true          // update value of specific key
    }
  }
}))

更新对象数组:

让我们假设您有一个待办事项应用程序,并且您正在以这种形式管理数据:

Updating array of objects:

Lets assume you have a todo app, and you are managing the data in this form:

this.state = {
  todoItems: [
    {
      name: 'Learn React Basics',
      status: 'pending'
    }, {
      name: 'Check Codebase',
      status: 'pending'
    }
  ]
}

要更新任何待办事项对象的状态,请在数组上运行一个映射并检查每个对象的某些唯一值,如果是condition=true,请返回具有更新值的新对象,否则返回同一对象.

To update the status of any todo object, run a map on the array and check for some unique value of each object, in case of condition=true, return the new object with updated value, else same object.

let key = 2;
this.setState(prevState => ({

  todoItems: prevState.todoItems.map(
    el => el.key === key? { ...el, status: 'done' }: el
  )

}))

建议:如果对象没有唯一值,则使用数组索引.

Suggestion: If object doesn't have a unique value, then use array index.

这篇关于在React中使用setState更新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:30