简体   繁体   中英

How to delete object from array?

I'm making abillity to follow/unfollow on my page using React/Redux. And I'm not fully understand how to make this. So, when the user following ' something ', reducer makes:

case FOLLOW_CITY: {
    return {
        ...state,
        followingCity: 
            [...state.followingCity,{
                id: shortid.generate(),
                cityAdded: action.city, 
                country: state.data.map(el => el.sys.country).toString(),
                name: state.data.map(el => el.name).toString(),
                followingStatus: true
            }]
    }
}

But I don't know how to make unfollow function. It has to delete object which I create above from array followingCity .

Also on the page, the title has to change:

{followingCity || followingCity.followingStatus === true // it doesnt' work
    ?   <div onClick={() => deleteCity()} className='add-button'> // how to create this?
            <span>followed</span>
            <i className="fa fa-check" aria-hidden="true"></i>
        </div>

    :   <div onClick={() => addCity(dailyData)} className='add-button'>
            <span>follow</span>
            <i className="fa fa-plus" aria-hidden="true"></i>
        </div>
}

You can filter the array and remove the object based on the id.

<div onClick={() => deleteCity(followingCity.id)} className='add-button'> // how to create this?
      <span>followed</span>
      <i className="fa fa-check" aria-hidden="true"></i>
</div>

Your deleteCity function can supply the id of the object and then for filtering you can do:

CASE DELETE_CITY: {
  return {
    ...state,
    followingCity: state.followingCity.filter(a => a.id !== theId)
  }
}

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