如何从当地人那里获得价值的反应

我向本地存储添加数据,如下所示:


 function handleSave(event) {

    let r = Math.random().toString(36).substring(7);

    const productInfo = {

      name: name,

      ean: ean,

      type: type,

      weight: weight,

      color: color,

      active: active,

    };

    // const productInfo2 = [name, ean, type, weight, color, active];

    localStorage.setItem(r, JSON.stringify(productInfo));

  }

我得到这样的本地存储映射:


{Object.entries(localStorage).map(([key, value]) => {


        return (

          <div style={style.gridItemsContainer}>

            <p>{value}</p>

            <p>{value.name}</p>

            <p>{value.name}</p>

            <p>{value.name}</p>

            <p>{value.name}</p>

            <input checked={value.active} type="checkbox"></input>

            <Link to={'/products/' + key}>VIEW</Link>

            <Link to={'/products/' + key + '/edit'}>EDIT</Link>

            <button>DELETE</button>

          </div>

        );

      })}

在第一段中,我得到这个:


{"name":"kede","ean":"12","type":"baldas","weight":"20","color":"ruda","active":""}

其他元素为空 我需要如何编辑我的代码,以便我可以通过键获取值,例如示例 value.name<p>


Qyouu
浏览 120回答 2
2回答

慕田峪7331174

您将获得需要解析它的 JSON 字符串。{Object.entries(localStorage).map(([key, valueJSON]) => {&nbsp; &nbsp; &nbsp; &nbsp;const value = JSON.parse(valueJSON);&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div style={style.gridItemsContainer}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>{value}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>{value.name}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>{value.name}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>{value.name}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p>{value.name}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input checked={value.active} type="checkbox"></input>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Link to={'/products/' + key}>VIEW</Link>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Link to={'/products/' + key + '/edit'}>EDIT</Link>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button>DELETE</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; })}

12345678_0001

我认为你的缺乏只是因为你需要它;)JSON.parse为了从本地存储中获取值,最好在构造函数/组件DidMount(如果是类组件)或useEffect方法(如果功能组件)中获取该值。例function MyComp() {&nbsp; const [myLocalStorageData, setMyLocalStorageData] = useState({})&nbsp; useEffect(()=> {&nbsp; &nbsp; //logic for getting a value from local storage stored under the key 'key'&nbsp; &nbsp; const data = localStorage.getItem('key')&nbsp; &nbsp; setMyLocalStorageData(JSON.parse(data))&nbsp; },[])&nbsp; ....}文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript