本地存储未更新

huangapple go评论70阅读模式
英文:

LocalStorage is not getting updated

问题

这是card.js文件的代码:

import React, { useState, useEffect } from 'react';

export default function Card(props) {
    let list = JSON.parse(localStorage.getItem("context"));
    const [setstyle, setsetstyle] = useState({
        color: 'black',
        background: 'rgb(238, 242, 241)'
    });

    const DeleteItem = (e) => {
        console.log("要删除的项 -> ", e);
        setsetstyle({
            display: 'none'
        });
        var filteredArray = list.filter(x => x.id !== e);
        localStorage.setItem('context', JSON.stringify(filteredArray));
        list = filteredArray;
    }

    const { id, images, name } = props;
    return (
        <div id={id} className='align displaySet' style={setstyle}>
            <main>
                <div className="border align">
                    <img src={images} alt="" />
                    <h3>{name}</h3>
                </div>
            </main>
            <button onClick={() => DeleteItem(id)}>删除</button>
        </div>
    )
}

问题是,当我点击“删除按钮”时,一个卡片被删除。但是当我点击另一张卡片时,我点击的那张卡片被删除,并被上一张卡片替换。

我认为问题在于localStorage一直在重新初始化。

如何解决这个问题?

英文:

This is the card.js,

import React, { useState, useEffect } from &#39;react&#39;
// import { PdtList } from &#39;./Cart&#39;;
export default function Card(props) {
    let list = JSON.parse(localStorage.getItem(&quot;context&quot;))
    const [setstyle, setsetstyle] = useState({
        color: &#39;black&#39;,
        background: &#39;rgb(238, 242, 241)&#39;
    })
    const DeleteItem = (e) =&gt; {
        console.log(&quot;to be deleted -&gt; &quot;, e);
        setsetstyle({
            display: &#39;none&#39;
        })
        var filteredArray = list.filter(x =&gt; x.id !== e);
        localStorage.setItem(&#39;context&#39;, JSON.stringify(filteredArray));
        list = filteredArray;
    }
    
    const { id, images, name } = props;
    return (
        &lt;div id={id} className=&#39;align displaySet&#39; style={setstyle} &gt;
            &lt;main&gt;
                &lt;div className=&quot;border align&quot;&gt;
                    &lt;img src={images} alt=&quot;&quot; /&gt;
                    &lt;h3&gt;{name}&lt;/h3&gt;
                &lt;/div&gt;
            &lt;/main&gt;
            &lt;button onClick={() =&gt; DeleteItem(id)} &gt;Delete&lt;/button&gt;
        &lt;/div&gt;
    )
}

The problem is when I am clicking on the Delete Button one card is getting deleted.

But when I am clicking on another card then the one I am clicking on is removed and replaced with the precious one.

I think the localStorage is reinitializing again and again

How can I resolve this?

答案1

得分: 1

像Konrad在评论中提到的那样,你应该使用useState来管理React组件内部的状态,然后使用useEffect钩子将localStorage与其连接,以便只在值更改时更新localStorage

import React, { useState, useEffect } from 'react';

export default function Card(props) {
    // 通过传递`localStorage.getItem('context')`,使初始状态为localStorage中存储的值
    const [list, setList] = useState(JSON.parse(localStorage.getItem('context')));
    const [setstyle, setsetstyle] = useState({
        color: 'black',
        background: 'rgb(238, 242, 241)'
    });

    // 此`useEffect`在`list`更改时更新localStorage
    useEffect(() => {
        localStorage.setItem('context', JSON.stringify(list));
    }, [list]);

    const DeleteItem = (e) => {
        console.log("要删除的项 -> ", e);
        setsetstyle({
            display: 'none'
        });
        setList(list.filter(x => x.id !== e));
    }

    const { id, images, name } = props;
    return (
        <div id={id} className='align displaySet' style={setstyle}>
            <main>
                <div className="border align">
                    <img src={images} alt="" />
                    <h3>{name}</h3>
                </div>
            </main>
            <button onClick={() => DeleteItem(id)}>删除</button>
        </div>
    )
}

请注意,上述代码是对你提供的React组件的翻译。

英文:

Like Konrad mentioned in the comments, you should use useState to manage the state inside a React component, and then connect localStorage with a useEffect hook to only update localStorage when the value changes:

import React, { useState, useEffect } from &#39;react&#39;
// import { PdtList } from &#39;./Cart&#39;;
export default function Card(props) {
    // Passing `localStorage.getItem(&#39;context&#39;)` makes the initial state the value stored in localStorage
    const [list, setList] = useState(JSON.parse(localStorage.getItem(&quot;context&quot;)))
    const [setstyle, setsetstyle] = useState({
        color: &#39;black&#39;,
        background: &#39;rgb(238, 242, 241)&#39;
    })
    // This `useEffect` updates localStorage whenever `list` changes
    useEffect(() =&gt; {
      localStorage.setItem(&#39;context&#39;, JSON.stringify(list))
    }, [list])
    const DeleteItem = (e) =&gt; {
        console.log(&quot;to be deleted -&gt; &quot;, e);
        setsetstyle({
            display: &#39;none&#39;
        })
        setList(list.filter(x =&gt; x.id !== e))
    }
    
    const { id, images, name } = props;
    return (
        &lt;div id={id} className=&#39;align displaySet&#39; style={setstyle} &gt;
            &lt;main&gt;
                &lt;div className=&quot;border align&quot;&gt;
                    &lt;img src={images} alt=&quot;&quot; /&gt;
                    &lt;h3&gt;{name}&lt;/h3&gt;
                &lt;/div&gt;
            &lt;/main&gt;
            &lt;button onClick={() =&gt; DeleteItem(id)} &gt;Delete&lt;/button&gt;
        &lt;/div&gt;
    )
}

huangapple
  • 本文由 发表于 2023年1月8日 22:42:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定