JSON.parse(localStorage.setItem("search",data))當我嘗試控制臺data它作業正常時,我有這行代碼,我只想將結果作為 JSON 保存到 localstorage,這是當前結果。

我有這個錯誤
SyntaxError: Unexpected token u in JSON at position 0
console.log() 的結果

uj5u.com熱心網友回復:
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);
};
uj5u.com熱心網友回復:
您的代碼完全落后。
您需要將資料字串化到JSON無法決議它從JSON,你需要對你傳遞值這樣做,以 setItem你不拿回值從 setItem(這是永遠undefined的,因此錯誤)。
localStorage.setItem("search",JSON.stringify(data))
也就是說,既然你說你在使用 React,我建議不要直接操作 localStorage。該useLocalStorage掛鉤,使生活變得更輕松。
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]; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/388585.html
標籤:javascript 反应
下一篇:按下按鈕時如何添加數值?
