在 React 中使用 setState 更新对象 [英] Updating an object with setState in React

查看:70
本文介绍了在 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?

推荐答案

有多种方法可以做到这一点,因为状态更新是一个 异步操作,所以要更新状态对象,我们需要使用updater 函数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.

假设您已将状态定义为:

Assume you have defined state as:

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

更新pizza对象的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'
    }
  ]
}

要更新任何 todo 对象的状态,请在数组上运行映射并检查每个对象的某个唯一值,在 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 更新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆