简体   繁体   English

如何在数组中的 Object 项目上设置状态

[英]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我想更新数组对象中关键心脏的 state 当心脏图标被按下时它变为红色所以为此我使用反应本机图标并且我使用 heart 和 hearto 在单击它时进行切换

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这里是 function 按下心脏图标时调用

 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现在在 onPress 做这个

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:编辑这个 function 如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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