React实现单按钮切换localStorage随机接口数据存储/删除功能问题
第一步:修正状态定义错误
原有状态存在类型不匹配、变量无法持久化的问题,修改如下:
import { useState, useEffect } from 'react'; // 状态定义修改 const [joke, setJoke] = useState(''); const [currentJokeId, setCurrentJokeId] = useState(null); // 原名key,语义化修改,初始值为null匹配字符串id类型 const [isFav, setIsFav] = useState(false); // 标记当前展示笑话是否已收藏 const [isRefreshActive, setIsRefreshActive] = useState(true); // 原isActive,修正布尔值类型,原来写的字符串"false"是错的
第二步:修正定时拉取逻辑,新增收藏状态校验
拉取到新笑话后,自动检查该id是否已存在localStorage,同步更新收藏标记:
useEffect(() =>{ // 只有刷新开启时才执行拉取 if (!isRefreshActive) return; const interval = setInterval(() => { getJoke() },3000); return () => clearInterval(interval); },[isRefreshActive]) // 依赖添加刷新状态,暂停时停止拉取 // 拉取笑话方法修改 const getJoke = () => { fetch('https://api.chucknorris.io/jokes/random') .then((res) => res.json()) .then((res) => { setCurrentJokeId(res.id); setJoke(res.value); // 检查当前笑话是否已收藏 setIsFav(!!localStorage.getItem(res.id)); }) .catch((err) => console.log(err)); }
第三步:合并存删逻辑为单切换方法
const toggleFav = () => { if (isFav) { // 已收藏状态,执行删除 localStorage.removeItem(currentJokeId); setIsFav(false); } else { // 未收藏状态,执行存储 const jokeData = JSON.stringify({ id: currentJokeId, content: joke }); localStorage.setItem(currentJokeId, jokeData); setIsFav(true); } }
第四步:修改按钮渲染逻辑
<button id="button" onClick={toggleFav}> {isFav ? '取消收藏' : '保存'} </button> <!-- 兼容原有暂停刷新功能 --> <button onClick={() => setIsRefreshActive(!isRefreshActive)}> {isRefreshActive ? '暂停刷新' : '开启刷新'} </button>
原有问题说明
- 原
removeItem方法只需传入存储key一个参数,不需要传序列化后的值,多余参数会被忽略 - 原
key状态初始值定义为数组,和接口返回的字符串id类型不匹配,会导致存取值异常 - 原
jokes变量是普通JS变量,每次组件渲染都会重置为空数组,无法存储历史收藏数据,这里改为每个笑话用自身id作为key单独存储,取值更简单 - 原
isActive状态赋值为字符串"false",布尔判断时会被识别为真值,改为布尔值类型避免逻辑错误
内容的提问来源于stack exchange,提问作者sollekram
相关产品推荐
相关产品推荐

