嗨,团队,我正在开发社交媒体应用程序。我正在测试我的登录页面功能。然后我遇到了截图中的错误,我附上供您参考。请帮我解决这个问题,我被困住了。
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>
);
};
问题是你正在尝试解析 json 上一些未定义的东西
JSON.parse(localStorage.getItem("user"))
当用户不在本地存储中时,该行与
相同JSON.parse(undefined)
要解决此问题,请将其分成两行
const storedUser = localStorage.getItem("user");
const [currentUser, setCurrentUser] = useState(storedUser ? JSON.parse(user) : null);