如何使用Lodash在数组中查找特定项目,然后使用setState()更新它?

时间:2019-06-03 05:24:09

标签: reactjs lodash setstate

adopt()组件中添加新方法 App ,该组件采用宠物(字符串)的 name 并修改在pets状态变量中表示该宠物的对象,因此宠物的adopted属性变为true

- Because this function will be called from an event handle, you'll want to define it as a _public class field_. Alternatively, you can wrap it in an arrow function when specified as a callback.

- Since you'll be wanting to modify elements in the state _based on_ the current state, you'll need to call the **`setState()`** method and pass it an (anonymous) callback function. This function should expect a parameter representing the current `state` and do the following:

    1. Then locate the correct pet Object inside the current `state.pets` array (the lodash [`.find()`](https://lodash.com/docs/4.17.10#find) function can help. Look at the examples for how you can find an object that has a particular property, such as the `name`).

    2. Assign a new value to that object's `adopted` property, indicating the pet is adopted.

    3. `return` an Object of values to change in the state—namely, that the `pets` value should now have the updated `state.pets` value.

这是我尝试过的方法,但我不知道如何结合这两种功能

 adopt(petName) {
    this.setState(() => {
      let pet = _.find(this.state.pets, ['name', petName]);
      return {
        adopted: true
      };
    });
  }

2 个答案:

答案 0 :(得分:0)

您应该将prevState传递给setState函数并找到宠物,为它添加一个“采用”的新attr并更新状态。 试试这个

adopt = (petName) => {
    this.setState((prevState) => {
        const findPet = _.find(prevState.pets, ['name', petName]);
        const adoptedPet = { ...findPet, adopted: true };
        return { pets: { ...prevState.pets, adoptedPet } };
    });
}

答案 1 :(得分:0)

使用findIndex会容易得多

adopt(petName) {
   this.setState(() => {
     let petIndex = _.findIndex(this.state.pets, ['name', petName]);
     pets[petIndex]={...pets[petIndex],adopted:true}}
     return this.state.pets
   });
 }