在反应中制作关注和取消关注按钮(更改按钮)

时间:2021-07-28 22:42:04

标签: reactjs react-redux react-hooks react-tsx

这是我的代码,我使用 Map 来渲染假期卡片,我需要添加关注和取消关注功能。我希望在按下“关注”后将其更改为仅在一张卡上的“取消关注”。 如果有人能帮助我,我将不胜感激。

export default function Vacations(){
    
    const [vacationsArray, setVacationsArray] = useState<IVacation[]>([]);
    const userDetails = useSelector((state: AppState) => state.userDetailes);


    useEffect(() => {
        axios.get("http://localhost:3001/vacations/")
        .then(data => {
            setVacationsArray(data.data)
            console.log(data.data)
        }).catch(e =>{
            console.log("failed to fetch data" + e)
        })
    },[]);

    const onUnfollowClicked = async()=>{
        console.log("Unfollowed")
    }

    const onFollowClicked = async (vacationId:any) =>{
        let userId = userDetails[0].id;
        await axios.post(`http://localhost:3001/followedVacations/${vacationId}`, {vacationId, userId});
      }

    return(
        <div className="vacationsContainer">
                {vacationsArray.map((vacation:any, key:number) =>(
                    <div key={key} className="vacation">
                        <button onClick={()=>onFollowClicked(vacation.id)}>Follow</button>
                        <button onClick={()=>onUnfollowClicked}>Unfollow</button>
                        <h1>{vacation.destination}</h1> <br></br>
                        <img width="300px" height="300px" src={vacation.image} alt="" /> <br></br>
                        <h3>Description:  <span>{vacation.description}</span></h3> <br></br>
                        <h3>Price:  <span>{vacation.price}$</span></h3> <br></br>
                        <h3>From:  <span>{vacation.startDate}</span></h3> <br></br> 
                        <h3>To:  <span>{vacation.endDate}</span></h3>
                    </div>
                ))}
        </div>
    )
}

1 个答案:

答案 0 :(得分:0)

一种方法是将所有订阅者的 ID(已关注用户的 ID)存储在后端的每个假期对象上:

// Example solution, assuming there is an array of users that subscribed
// for each vacation (e.g.
// {
//   id: '',
//   image: '',
//   description: '',
//   price: '',
//   startDate: '',
//   endDate: '',
//   subscribers: ['id1', 'id2', 'id4', ...]
// })

return (
  <div className="vacationsContainer">
    {vacationsArray.map((vacation: any, key: number) => {
      let onClickFunction = null;
      let buttonText = "";

      if (
        vacation?.subscribers.length &&
        vacation.subscribers.includes(userDetails[0].id)
      ) {
        onClickFunction = () => onUnfollowClicked(vacation.id);
        buttonText = "Unfollow";
      } else {
        onClickFunction = () => onFollowClicked(vacation.id);
        buttonText = "Follow";
      }

      return (
        <div key={key} className="vacation">
          <button onClick={onClickFunction}>{buttonText}</button>
          <h1>{vacation.destination}</h1> <br></br>
          <img width="300px" height="300px" src={vacation.image} alt="" />
          <br></br>
          <h3>
            Description: <span>{vacation.description}</span>
          </h3>
          <br></br>
          <h3>
            Price: <span>{vacation.price}$</span>
          </h3>
          <br></br>
          <h3>
            From: <span>{vacation.startDate}</span>
          </h3>
          <br></br>
          <h3>
            To: <span>{vacation.endDate}</span>
          </h3>
        </div>
      );
    })}
  </div>
);

如果您想要的只是有几个按钮可以在点击时从“关注”切换到“取消关注”,反之亦然,那么您只需要在本地状态中存储一组 followVacationIds,然后添加或删除假期单击每个特定按钮时从中获取 id。

仅根据您提供的信息,我无法确定您要查找的内容。希望我上面实现的代码是解决您问题的正确方法。否则,请使用更多信息编辑您的问题,例如您正在获取的数据的结构,我将使用适当的解决方案编辑我的答案。