【问题标题】:How to use Lodash _.find() and setState() to change a value in the state?如何使用 Lodash _.find() 和 setState() 更改状态中的值?
【发布时间】:2019-06-03 03:53:03
【问题描述】:

我正在尝试使用 lodash 的 find 方法来确定基于一个属性的索引。在我的情况下,这是宠物的名字。之后,我需要使用 setState 将采用的值更改为 true。然而问题是;我不明白如何结合 setState 和 _.find()

到目前为止,我已经写好了这篇文章。我的主要问题是弄清楚如何完成这个。

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

目前这没有任何作用,因为它是错误的,但我不知道如何从那里开始!

【问题讨论】:

    标签: reactjs lodash setstate


    【解决方案1】:

    在 React 中,您通常不想改变状态。为此,您需要重新创建 pets 数组和采用的项。

    您可以使用_.findIndex()(或香草JS Array.findIndex())来查找项目的索引。然后将数组前后切片,并使用spread在状态下创建一个新数组,带有“更新”项:

    adopt(petName) {
      this.setState(state => {
        const petIndex = _.findIndex(this.state.pets, ['name', petName]); // find the index of the pet in the state
    
        return [
          ...state.slice(0, petIndex), // add the items before the pet
          { ...state[petIndex], adopted: true }, // add the "updated" pet object
          ...state.slice(petIndex + 1) // add the items after the pet
        ];
      });
    }
    

    你也可以使用Array.map()(或lodash的_.map()):

    adopt(petName) {
      this.setState(state => state.map(pet => pet.name === petName ? ({ // if this is the petName, return a new object. If not return the current object
        ...pet,
        adopted: true
      }) : pet));
    }
    

    【讨论】:

      【解决方案2】:

      将您的收养功能更改为

      adopt = petName => {
        let pets = this.state.pets;
        for (const pet of pets) {
          if (!pet.adopted && pet.name === petName) {
            pet.adopted = true;
          }
        }
        this.setState({
          pets
        });
      };
      
      // sample pets array
      
      let pets = [
        {
          name: "dog",
          adopted: false
        },
        {
          name: "cat",
          adopted: false
        }
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-23
        • 1970-01-01
        • 2019-07-19
        • 2015-07-25
        • 2019-07-10
        • 2020-06-05
        • 2019-12-22
        • 1970-01-01
        相关资源
        最近更新 更多