为什么我的Axios获得方法不更新我的反应usestate?

问题描述 投票:0回答:1
所以我的app.jsx的代码为

import Navbar from "./components/Navbar"; import TodoList from "./components/TodoList"; import Authentication from "./components/Authentication"; import Sidebar from "./components/Sidebar"; import { useEffect, useState } from "react"; import AccountCenter from "./components/AccountCenter"; import axios from "axios"; function App() { // decides if its gonna show the todo list or not const [showTodo, setShowTodo] = useState(true); // decides if its gonna show the account center or not const [showAccCenter, setShowAccCenter] = useState(false); // If its true thn shows the signup form and if its false thn shows the login form const [signUp, setSignUp] = useState(true); // Shows if user logged in or not const [loggedIn, setLoggedIn] = useState(false); // Save user data const [userData, setUserData] = useState({}); // Function to authenticate const checkUserAuth = async () => { try { // Send a request to the protected route to check if the user is still logged in const response = await axios.get( "https://doit-rn-backend.onrender.com/api/auth", { withCredentials: true }, ); // If the response is successful, the user is logged in and the user data is saved setUserData(response.data); setLoggedIn(true); } catch { // If authentication fails thn it asks user to login again setLoggedIn(false); setShowTodo(false); } }; useEffect(() => { console.log(userData) }, [userData]); // Authenticate on page load useEffect(() => { checkUserAuth(); }, []); // Fetches loggedIn data from localStorage useEffect(() => { const loggedInData = localStorage.getItem("loggedIn"); if (loggedInData === "true") { setLoggedIn(true); } else { setLoggedIn(false); } }, []); return ( <div className="flex h-full w-full flex-col items-center justify-center border-2 border-black bg-[#D6D3C0] sm:h-4/5 sm:w-3/4"> <Navbar /> <div className="flex h-full w-full gap-6"> {loggedIn && ( <Sidebar setShowTodo={setShowTodo} setShowAccCenter={setShowAccCenter} /> )} {showTodo && <TodoList loggedIn={loggedIn} userData={userData} />} {showAccCenter && ( <AccountCenter setLoggedIn={setLoggedIn} setSignUp={setSignUp} loggedIn={loggedIn} showTodo={showTodo} userData={userData} /> )} {loggedIn === false && ( <Authentication signUp={signUp} setSignUp={setSignUp} setShowTodo={setShowTodo} /> )} </div> </div> ); } export default App;
因此,此代码仍在开发中,但是您可以看到,当我从后端服务器中获取数据并记录响应时。数据输出为

Object { username: "aaaa", userId: "67a5ec5abd38bc1cf6a49c4d" }


但我的使用效率CLG的输出或使用Console.log(userData)输出是对象{}或空白时,为什么我的setUserData(response.data)不起作用?为什么不更新UserData的usestate?

i试图将CLG放在SetuserData之后(response.data);它仍然显示为空白,这就是为什么我使用使用clg的使用效果。

TryConsole Lotagging Response.DATA,检查您是否得到任何响应和/或检查浏览器中的Network Tab的响应。
reactjs node.js express axios mern
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.