如何在数组内的对象项上设置状态

时间:2019-10-08 13:00:23

标签: javascript arrays react-native

当心脏图标按下时,我想更新数组对象中关键心脏的状态,使其变为红色,为此,我正在使用react native图标,并且在单击时使用heart和hearto进行切换

这是代码:

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

此处是按下心脏图标时调用的功能

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

这是心脏图标代码

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

请帮助我如何在单击时将心脏更新为心脏而不是心脏

2 个答案:

答案 0 :(得分:5)

您可以通过以下方法轻松实现

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
            }
}

现在在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

    })
  })
};

现在像这样渲染

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

希望对您有帮助

答案 1 :(得分:1)

按如下方式编辑此功能:

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