【问题标题】:How to save json in LocalStorage using Reactjs?如何使用 Reactjs 在 LocalStorage 中保存 json?
【发布时间】:2021-12-21 13:22:21
【问题描述】:

当我尝试控制台 data 时,我有这行代码 JSON.parse(localStorage.setItem("search",data)) 它工作正常,我只想将结果作为 JSON 保存到本地存储,这是当前结果。

我有这个错误

 SyntaxError: Unexpected token u in JSON at position 0

console.log() 的结果

【问题讨论】:

  • 当你 console.log(data); 看起来你的 data 不是一个有效的 JSON 字符串时你会得到什么
  • @kiranvj 等一下,我会发图
  • localStorage.setItem("search", JSON.stringify(data))

标签: javascript reactjs


【解决方案1】:

你的代码完全倒退了。

您需要将数据字符串化 JSON,而不是从 JSON 解析它,并且您需要对传递的值进行 to @ 987654322@ 不是您 setItem(始终为undefined,因此出现错误)返回的值。

localStorage.setItem("search",JSON.stringify(data))

也就是说,既然你说你使用的是 React,我建议不要直接操作 localStorage。 useLocalStorage hook 让生活更轻松。

import { useState } from "react";

// Usage
function App() {
  // Similar to useState but first arg is key to the value in local storage.
  const [name, setName] = useLocalStorage("name", "Bob");

  return (
    <div>
      <input
        type="text"
        placeholder="Enter your name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
    </div>
  );
}

// Hook
function useLocalStorage(key, initialValue) {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState(() => {
    try {
      // Get from local storage by key
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  });

  // Return a wrapped version of useState's setter function that ...
  // ... persists the new value to localStorage.
  const setValue = (value) => {
    try {
      // Allow value to be a function so we have same API as useState
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      // Save state
      setStoredValue(valueToStore);
      // Save to local storage
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      // A more advanced implementation would handle the error case
      console.log(error);
    }
  };

  return [storedValue, setValue];
}

【讨论】:

    【解决方案2】:

    Quentin 的回答是对的,但你也可以创建一个实用程序来管理本地存储中的数据。

    export const saveToLocal = (key, data) => {
        localStorage.setItem(key, JSON.stringify(data));
    };
    
    export const getFromLocal = (key) => {
        const data = localStorage.getItem(key);
        return JSON.parse(data);
    };
    
    export const removeFromLocal = (key) => {
        localStorage.removeItem(key);
    };
    

    【讨论】:

    • 在使用 React 时,最好将实用程序编写为钩子。
    • @Quentin 是的,但正如我从我的经验中了解到的那样,让事情变得简单可以做得更好,为它编写一个钩子并不能帮助您提高性能或可读性,而是增加了无用的代码我认为
    • 可能仍然需要该钩子中的所有复杂性,只是它不会那么有条理。
    • 例如,您的代码在尝试将其解析为 JSON 之前缺少检查以确保密钥存在。所以getFromLocal 可以很容易地抛出异常。
    • @Quentin 错误处理可以根据用例或要求轻松添加,我认为这没什么大不了的
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    相关资源
    最近更新 更多