import {createContext, useEffect, useReducer} from 'react';
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem('user')) || null,
loading: false,
error: null,
};
export const AuthContext = createContext(INITIAL_STATE);
const AuthReducer = (state, action) => {
switch (action.type) {
case 'LOGIN_START':
return {
user: null,
loading: true,
error: null,
};
case 'LOGIN_SUCCESS':
return {
user: action.payload,
loading: false,
error: null,
};
case 'LOGIN_FAILURE':
return {
user: null,
loading: false,
error: action.payload,
};
case 'LOGOUT':
return {
user: null,
loading: false,
error: null,
};
default:
return state;
}
};
export const AuthContextProvider = ({children}) => {
const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
useEffect(() => {
localStorage.setItem('user', JSON.stringify(state.user));
}, [state.user]);
return (
<AuthContext.Provider
value={{
user: state.user,
loading: state.loading,
error: state.error,
dispatch,
}}
>
{children}
</AuthContext.Provider>
);
};
我正在学习反应和错误"Uncaught SyntaxError: "undefined"JSON"出现
这是代码中涉及JSON的部分。我正在使用上下文api实现登录功能。在这里输入图像描述,请帮助我解决这个错误。谢谢你。
您的localStorage中似乎有未定义的用户键值。可能通过使用值为undefined
的变量来设置值。请检查一下!