ReactJS:如何将LocalStorage中的字符串解析为数组(原存储为useState状态值)
Hey there! I see the issue you're running into—let's break this down and get it sorted.
The Root Problem
When you pull data from localStorage, it always comes back as a string (even if you stored an object using JSON.stringify). Right now, you're trying to access userDetails.canBook directly on that string, which won't work because strings don't have a canBook property. Also, quick correction: you stored an object, not an array, so we'll be parsing it back into an object, not an array.
The Solution: Use JSON.parse()
To turn that string back into a usable JavaScript object, you need to use JSON.parse(). You should also add a check for null (in case the userDetails key doesn't exist in localStorage yet) to avoid unexpected errors.
Here's your updated bookSlot function:
const bookSlot = () => { // Get the raw string from localStorage const userDetailsStr = localStorage.getItem("userDetails"); // Handle the case where no data exists under this key if (!userDetailsStr) { console.log("No user details found in localStorage"); return null; } // Parse the string back into a JavaScript object const userDetails = JSON.parse(userDetailsStr); // Now you can safely access the canBook property if (userDetails.canBook !== 0) { return userDetails; } // Return a fallback value if canBook is 0 return null; };
Key Tips for Safety
- Always check for null: If the
userDetailskey hasn't been set yet,localStorage.getItem()returnsnull. WhileJSON.parse(null)won't throw an error, handling this case explicitly makes your code more predictable. - Use strict equality:
!==(strict not equal) avoids weird type coercion issues. For example, ifcanBookwas accidentally stored as a string "0",!= 0would incorrectly treat it as equal to 0, but!== 0catches the type mismatch. - Validate object structure (optional): For extra robustness, add checks to ensure the parsed object has the properties you need:
if (typeof userDetails === 'object' && userDetails !== null && 'canBook' in userDetails) { // Proceed with your check for canBook }
内容的提问来源于stack exchange,提问作者Max Andersson

