如何从本地存储中获取价值

时间:2020-06-08 10:14:48

标签: javascript reactjs local-storage

我这样将数据添加到localStorage:

 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));
  }

我得到的localStorage映射如下:

{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":""}

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

2 个答案:

答案 0 :(得分:2)

您正在获取需要解析的JSON字符串。

{Object.entries(localStorage).map(([key, valueJSON]) => {
       const value = JSON.parse(valueJSON);

        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>
        );
      })}

答案 1 :(得分:0)

我认为您的缺乏只是因为您需要JSON.parse;)

从本地存储中获取值最好是在构造函数/ componentDidMount(如果是类组件)或useEffect方法(如果是功能组件)中获取

示例

function MyComp() {
  const [myLocalStorageData, setMyLocalStorageData] = useState({})
  useEffect(()=> {
    //logic for getting a local storage value
    const data = localStorage.getitem('key')
    setMyLocalStorageData(JSON.parse(data))
  },[])
  ....
}

文档:

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage