简体   繁体   English

React JS:从本地存储中删除一个项目

[英]React JS: remove an item from the localStorage

I'm trying to make a workable App where you get from an API some data and that data is randomly changes every 3 seconds and with a button the user can print the data and by pressing again it stops, i have managed to complete this(as seen bellow) part(btw new to react js):我正在尝试制作一个可行的应用程序,您可以从 API 获得一些数据,并且该数据每 3 秒随机更改一次,并且用户可以使用按钮打印数据并再次按下它停止,我已经设法完成了这个(如下所示)部分(顺便说一句新反应js):

 useEffect(() =>{ const interval = setInterval(() => { getJoke() },3000); return () => clearInterval(interval); },[]) //fetch the jokes function const getJoke = (() => { fetch('https://api.chucknorris.io/jokes/random').then((res) => res.json()).then((res) => { setKey(res.id); setJoke(res.value); }).catch((err) => console.log(err)); })

i have also made a button where the user can save the data(which randomly appears every 3 sec) on the localStorage of the browser as seen bellow..我还制作了一个按钮,用户可以在其中将数据(每 3 秒随机出现一次)保存在浏览器的 localStorage 上,如下所示。

 const addJokeFav = (() => { jokes.push(joke); const jokesJsonified = JSON.stringify(jokes); localStorage.setItem(key, jokesJsonified); }) bellow the render code <button id="button" onClick={()=>{addJokeFav()}}>Save!</button>

but i would like to have only one button where he save one data coming randomly and every 3 seconds, and if he repress the button the data will be deleted from the localStorage.但我只想有一个按钮,他在其中随机保存一个数据,每 3 秒一次,如果他重新按下按钮,数据将从 localStorage 中删除。 i have this function here which i dont seem to make it work.我在这里有这个 function 我似乎没有让它工作。

 const remJokeFav = (() => { const jokesJsonified = JSON.stringify(jokes); localStorage.removeItem(key, jokesJsonified); })

it seems that is trying to remove and item that is not there cause of the key, which i take it with setKey(res.id) on the response, on the code above in the first snippet.似乎正在尝试删除不存在密钥原因的项目,我在响应中使用 setKey(res.id) 在第一个片段中的上述代码中将其删除。 my App variables are bellow.我的应用程序变量如下。

 const [joke, setJoke] = useState(); const [key, setKey] = useState([]); const [isActive, setActive] = useState("false"); const jokes = [];

Thanks for any help regarding the situation!感谢您提供有关情况的任何帮助!

The problem looks to be with localStorage.removeItem(key, jokesJsonified);问题似乎与localStorage.removeItem(key, jokesJsonified); removeItem just needs the key and not the value. removeItem 只需要键而不是值。

Also there is unnecessary rerender on setting jokes array.在设置笑话数组时也有不必要的重新渲染。 Make jokes array as ref instead of state.将笑话数组设为 ref 而不是 state。

Here is an working example in codesandbox这是代码沙箱中的一个工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM