首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >“未定义”是无效的JSON

“未定义”是无效的JSON
EN

Stack Overflow用户
提问于 2022-08-23 09:08:24
回答 6查看 3.7K关注 0票数 0

我的控制台出了这个错误。我做的最后一件事就是注册一个用户!现在我得到了这个错误,我不知道为什么!我想它说的“用户”不是一个有效的JSON,为什么呢?我哪里出错了!

代码语言:javascript
运行
复制
> Uncaught SyntaxError: "undefined" is not valid JSON
>     at JSON.parse (<anonymous>)
>     at ./src/context/Context.js (Context.js:5:1)
>     at options.factory (react refresh:6:1)
>     at __webpack_require__ (bootstrap:24:1)
>     at fn (hot module replacement:62:1)
>     at ./src/components/topbar/TopBar.jsx (SideMenu.jsx:23:1)
>     at options.factory (react refresh:6:1)
>     at __webpack_require__ (bootstrap:24:1)
>     at fn (hot module replacement:62:1)
>     at ./src/App.js (return-arrow.svg:26:1)

错误所在的Context.js 。见const INITIAL_STATE

代码语言:javascript
运行
复制
import { createContext, useEffect, useReducer } from "react";
import Reducer from "./Reducer";

const INITIAL_STATE = {
  user: JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
  error: false,
};

export const Context = createContext(INITIAL_STATE);
export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

  useEffect(() => {
    localStorage.setItem("user", JSON.stringify(state.user));
  }, [state.user]);

  return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};

Context 同样适用于登录,并运行良好的

代码语言:javascript
运行
复制
export const RegisterStart = (userCredentials) => ({
  type: "REGISTER_START",
});

export const RegisterSuccess = (user) => ({
  type: "REGISTER_SUCCESS",
  payload: user,
});

export const RegisterFailure = () => ({
  type: "REGISTER_FAILURE",
});

注册页中的函数

代码语言:javascript
运行
复制
const handleSubmit = async (e) => {
    e.preventDefault();
    dispatch({ type: "REGISTER_START" });
    setError(false);
    try {
      const res = await axios.post("/register", {
        username,
        email,
        password,
        repeatPassword,
      });
      dispatch({ type: "REGISTER_SUCCESS", payload: res.data });
    } catch (err) {
      dispatch({ type: "REGISTER_FAILURE" });
      setError(true);
    }
  };
EN

回答 6

Stack Overflow用户

发布于 2022-08-23 09:14:49

在运行这段代码时,localStorage中似乎没有“用户”条目。

因此,它会引发一个错误,因为您正在尝试JSON.parse一个undefined值。

要使它工作,我们可以检查“用户”是否存在于localStorage中,然后再尝试解析它。

代码语言:javascript
运行
复制
const INITIAL_STATE = {
  user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : null,
  isFetching: false,
  error: false,
};

我们在这里要做的是首先检查localStorage.getItem("user")的返回值是否真实,而不是undefined

如果你想更明确,你也可以把它写成-

代码语言:javascript
运行
复制
user: localStorage.getItem("user") !== undefined ? JSON.parse(localStorage.getItem("user")) : null,
票数 0
EN

Stack Overflow用户

发布于 2022-08-23 09:16:03

初始状态最初是未定义的,因为您还没有设置项user。您可以首先检查user是否存在于localStorage中:是的,=>返回用户,返回默认值为null

代码语言:javascript
运行
复制
const INITIAL_STATE = {
  user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) || null,
  isFetching: false,
 error: false,
};
票数 0
EN

Stack Overflow用户

发布于 2022-09-14 07:29:01

那么,我们如何编写代码来避免这种现金错误呢?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73455972

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档