You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NASA每日图片应用如何实现点赞按钮与对应日期图片的状态绑定

问题根源

你现在的Likes组件只在localStorage里存储了单个全局的点赞状态,没有和当前展示的图片日期做绑定,所以切换日期后状态不会跟着变。

改造步骤

1. 改造PictureInfo组件,给Likes传递当前图片日期

找到PictureInfo里引用Likes的行,改成传递currentDate参数:

// 原来的 <Likes /> 替换成下面的
<Likes currentDate={props.date} />

2. 重写Likes组件逻辑,支持按日期存储点赞状态

直接替换整个Likes组件的代码即可,修改点说明:

  • 接收currentDate作为入参
  • localStorage存储结构改为对象,以日期为key存储对应点赞状态
  • 每次切换日期时自动读取对应日期的点赞状态
import React, {useState, useEffect} from "react";
import ToggleHearts from "./ToggleHearts"
import {
    Button,
    Typography,
} from "@mui/material";
import {makeStyles} from "@mui/styles";

const useStyles = makeStyles((theme) => ({
  button: {
    ...theme.typography.buttons,
    fontFamily: "Orbitron",
    padding: "0.7em",
    fontSize: "1.5em",
    width: "3.2em",
    height: "3.2em",
    background: theme.palette.primary.mainGradient,
    border: "2px solid pink",
    ":hover": {
      background: theme.palette.secondary.mainGradient,
    },
  },
}));

// 新增入参 currentDate
const Likes = ({currentDate}) => {
    const classes = useStyles();
    const [liked, setLiked] = useState(false)

    // 读取所有点赞记录
    const getAllLikes = () => {
      const stored = window.localStorage.getItem("apodLikes");
      return stored ? JSON.parse(stored) : {};
    }

    const handleChangeHeart = () => {
        const newLikedStatus = !liked;
        setLiked(newLikedStatus);
        // 更新存储里对应日期的状态
        const allLikes = getAllLikes();
        allLikes[currentDate] = newLikedStatus;
        window.localStorage.setItem("apodLikes", JSON.stringify(allLikes));
    };
   
    // 切换日期时,读取对应日期的点赞状态
    useEffect(() => {
      if(!currentDate) return;
      const allLikes = getAllLikes();
      setLiked(allLikes[currentDate] || false);
    }, [currentDate])

    return (
      <Button
        className={classes.button}
        variant="contained"
        onClick={handleChangeHeart}
      >
        <Typography style={{ fontFamily: "Orbitron" }}>
          <ToggleHearts liked={liked}/>
        </Typography>
      </Button>
    );
}

export default Likes

额外优化建议

如果担心日期格式不统一,可以在传递给Likes前统一格式化为YYYY-MM-DD格式,比如在PictureInfo里传递的时候写成:

<Likes currentDate={moment(props.date).format("YYYY-MM-DD")} />

可以避免不同格式的日期被识别为不同key的问题。

内容的提问来源于stack exchange,提问作者Natsuko Izuki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:45:05