reactjs 未捕获的语法错误:“[object Object]”在JSON中不是有效的JSON,parse(< anonymous>)

fcg9iug3  于 2023-05-17  发布在  React
关注(0)|答案(3)|浏览(782)
Uncaught SyntaxError: "[object Object]" is not valid JSON
    at JSON.parse (<anonymous>)  
vendors~main.chunk.js:32926 The above error occurred in the <Home> component:

    at Home (http://localhost:3000/static/js/main.chunk.js:1640:99)
    at RenderedRoute (http://localhost:3000/static/js/vendors~main.chunk.js:131876:5)
    at Routes (http://localhost:3000/static/js/vendors~main.chunk.js:132298:5)
    at App
    at Router (http://localhost:3000/static/js/vendors~main.chunk.js:132236:15)
    at BrowserRouter (http://localhost:3000/static/js/vendors~main.chunk.js:130557:5)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
console.<computed> @ vendors~main.chunk.js:32926
localhost/:1 Uncaught (in promise) SyntaxError: "[object Object]" is not valid JSON
    at JSON.parse (<anonymous>)
    at Home (main.chunk.js:1643:72)
  
VM23:2 Uncaught ReferenceError: process is not defined
  

**CODE**

const Home =()=> { const scrollRef = useRef(null); const userInfo = localStorage.getItem('user ')!== 'undefined'?JSON.parse(localStorage.getItem('user ')):public void run(); useEffect(()=> { const query = userQuery(userInfo?.sub);

client.fetch(query).then((data) => {
       setUser(data[0]);
   })
   }, []);

   useEffect(()=>{
       scrollRef.current.scrollTo(0, 0);
    
     },[])
to94eoyn

to94eoyn1#

当你在本地存储器中存储数据时,使用JSON.stringify(data)而不是直接存储数据。

kyxcudwk

kyxcudwk2#

看起来你从localStorage.getItem('user')中得到的字符串"[object Object]"基本上是无用的。记住localstorage就像字典一样,但是只存储字符串而不是对象。正如@Naman Agrawal所指出的,在将数据存储到本地存储之前,先将其转换为字符串

localstorage['user'] = JSON.stringify(data)
rxztt3cl

rxztt3cl3#

为了更准确地定位错误,需要更多的信息。如果我们假设在JSON.parse(localStorage.getItem('user'))期间发生错误,那么这是因为在写入期间使用了Object。本地存储添加了对象datalocalStorage.setItem('user', data)(完成我们的订单)
localStorage.getItem(data)// output👉:[object Object]JSON.parse(localStorage.getItem('user'))// output👎“[object Object]”不是有效的JSON
修复:
localStorage.setItem('user',JSON.stringify(data));
或:
localStorage['user'] = JSON.stringify(data);

相关问题