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

How to use Lodash to find a specific item in an array and then use setState() to update it?

App 组件中添加一个新方法 adopt() 来接收宠物的 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
      };
    });
  }

您应该将 prevState 传递给 setState 函数并找到宠物,向其添加新的属性 'adopted' 并更新状态。 试试这个

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

如果使用 findIndex 就容易多了

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