如何使用Lodash _.find()和setState()更改状态中的值? [英] How to use Lodash _.find() and setState() to change a value in the state?

查看:137
本文介绍了如何使用Lodash _.find()和setState()更改状态中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use lodash's find method to determine an index based on one attribute. In my case this is pet name. After that I need to change the adopted value to true using setState. The problem is however; I do not understand how to combine setState and _.find()

截至目前,我已经写了这篇文章.我的主要问题是弄清楚该如何完成.

As of right now I have this written. My main issue is figuring out how to finish this.

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

此刻它什么都不做,因为它是错误的,但是我不知道该怎么走!

This does nothing at the moment as it is wrong, but I don't know how to go from there!

推荐答案

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

In React you usually don't want to mutate the state. To do so, you need to recreate the pets array, and the adopted item.

您可以使用 _.findIndex() (或香草JS

You can use _.findIndex() (or vanilla JS Array.findIndex()) to find the index of the item. Then slice the array before and after it, and use spread to create a new array in the state, with the "updated" item:

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() ):

You can also use Array.map() (or lodash's _.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));
}

这篇关于如何使用Lodash _.find()和setState()更改状态中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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