Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - how can I read multiple keys from localStorage with React?

I am saving several keys in the localStorage with the following line

code

and I want to iterate them to display the products in a cart. but I can't get it to show all the keys

const arre = Object.keys(localStorage)

const recorreArray = (arr) => {
  for(let i=0; i <= arr.length; i++){
  console.log(arr[i]);
  }
}

const prueba = recorreArray(arre)
  

  const stringifiedProducts = localStorage.getItem(arre)
  const products = JSON.parse(stringifiedProducts) 
question from:https://stackoverflow.com/questions/65946657/how-can-i-read-multiple-keys-from-localstorage-with-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

first you need to make an object which have your all keys. and then set them to local storages instead of having different keys.

for example

 var myobj={
 "firstData":"data1",
 "secondData":"data2",
 "thirdData": "data3"
 }

now set this data to localStorage

 localStorage.setItem('MyObject', JSON.stringify(myobj));

now set this data From localStorage

 var AllKeysFromLocalStorage = localStorage.getItem('MyObject');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...