与“未定义”相关的错误不是有效的 JSON

问题描述 投票:0回答:1

嗨,团队,我正在开发社交媒体应用程序。我正在测试我的登录页面功能。然后我遇到了截图中的错误,我附上供您参考。请帮我解决这个问题,我被困住了。

import axios from "axios";

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
    const [currentUser, setCurrentUser] = useState(
        JSON.parse(localStorage.getItem("user")) || null
    );

    console.log(localStorage.getItem("user"));

    const login = async (inputs) => {
        const res = await axios.post("http://localhost:8800/api/auth/login", inputs, {
            withCredentials: true,
        });
        setCurrentUser(res.data);
    };

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

    return (
        <AuthContext.Provider value={{ currentUser, login }}>
            {children}
        </AuthContext.Provider>
    );
};
reactjs json parsing
1个回答
0
投票

问题是你正在尝试解析 json 上一些未定义的东西

JSON.parse(localStorage.getItem("user"))

当用户不在本地存储中时,该行与

相同
JSON.parse(undefined)

要解决此问题,请将其分成两行

const storedUser = localStorage.getItem("user");
const [currentUser, setCurrentUser] = useState(storedUser ? JSON.parse(user) : null);
© www.soinside.com 2019 - 2024. All rights reserved.