繁体   English   中英

如何修复错误 How To Fix Unexpected token u in JSON at position 0

[英]How can I fix the error How To Fix Unexpected token u in JSON at position 0

我的用户 reducer 代码出现错误。 这就是我所做的。

export const userReducer = (
  state = localStorage.getItem('user') !== undefined
    ? JSON.parse(localStorage.getItem('user'))
    : null,
  action
) => {
  switch (action.type) {
    case 'LOGGED_IN_USER':
      return action.payload
    case 'LOGOUT':
      return action.payload
    default:
      return state
  }
}

我不知道我是否很好地声明了 state。 我觉得这就是问题所在。

我曾尝试将我的 state 声明为

export const userReducer = (
  state = localStorage.getItem('user') 
  ? JSON.parse(localStorage.getItem('user')) 
  : null, 
  action
) => {
  switch (action.type) {
    case 'LOGGED_IN_USER':
      return action.payload
    case 'LOGOUT':
      return action.payload
    default:
      return state
  }
}

我仍然遇到同样的错误,我的页面无法加载。 它呈现一个空白屏幕,并在控制台中显示错误。

这是一个“安全”的 JSON 解析器,它可以处理很多古怪的/损坏的/坏的/损坏的 JSON:

function jparse(str) { 
    var result = null; 
    try { 
        result = JSON.parse(str) 
    } catch (e) {
        // ignore
    } 
    if (!result) {
        try {
            result = Function('return (' + str + ")")();
        } catch(e){
            // ignore
        }
    }
    return result;
}

console.log( jparse(null) );            // null
console.log( jparse('{bob:"er"}') );    // {bob: 'er'}
console.log( jparse('{\'bob\':"er"}') );// {bob: 'er'}
console.log( jparse('{bob:}') );        // null
console.log( jparse(0) );               // 0
console.log( jparse(false) );           // false
console.log( jparse(undefined) );       // undefined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM