简体   繁体   中英

How to setState on Object item within array

I want to update state of key heart in the array's objects when the heart icon pressed it changes to red so for this I'm using react native icons and i'm using heart and hearto to switch when click on it

here is the code:

state = {      
          localAdversiment: [
            {
              title: "Ecloninear 871",
              image: require("../../assets/images/truck_image.png"),
              year: "2015",
              type: "Truck",
              status: "new",
              price: "$ 2000",
              heart: "hearto"
            }

Here it function which is called when heart icon pressed

 handleFavourite = index => {
    const { heart } = this.state.localAdversiment[index];
    this.setState(
      {
        heart: "heart"
      }
    );
  };

here is the heart icon code

<TouchableOpacity onPress={() => this.handleFavourite(index)}>
                <Icon
                  name={item.heart}
                  type={"AntDesign"}
                  style={{ fontSize: 18 }}
                />
              </TouchableOpacity>

kindly help me how to update heart as heart instead of hearto when clicked

You can do it easily by following approach

state = {      
          localAdversiment: [
            {
              id: 0,
              title: "Ecloninear 871",
              image: require("../../assets/images/truck_image.png"),
              year: "2015",
              type: "Truck",
              status: "new",
              price: "$ 2000",
              heart: "hearto",
              selected: false
            }
}

now in onPress do this

handleFavourite = (item) => {
   const { id } = item;
   this.setState({
       localAdvertisement: this.state.localAdvertisement.map((item) => {
         if(item.id === id){
           return {
              ...item,
              selected: !item.selected  
           }
         }

         return item

    })
  })
};

Now render like this

             <TouchableOpacity onPress={() => this.handleFavourite(item)}>
                <Icon
                  name={item.selected ? "heart" : 'hearto'}
                  type={"AntDesign"}
                  style={{ fontSize: 18 }}
                />
              </TouchableOpacity>

Hope it will help you

Edit this function as follows:

handleFavourite = index => {
    let updatedlocalAdversimentStates = this.state.localAdversiment;
    updatedlocalAdversimentStates[index].heart = "heart";
    this.setState(
      {
        localAdversiment: updatedlocalAdversimentStates
      }
    );
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM