每當我訪問“/”路由并在檢查中轉到網路部分時,我都會看到一堆請求轉到“/api/checkauth”。當我訪問“/”路由時,我只呼叫一次請求“/api/checkauth”。也許與它有關element={...}。我不知道如何解決這個問題。
這是我訪問一次時在網路部分看到的
import './App.css';
import { React, useState } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Login from "./components/Login";
import Signup from "./components/Signup";
import Feed from "./components/User/Feed";
import UserProfile from "./components/User/UserProfile";
const axios = require("axios");
function App() {
const [isAuth, setAuth] = useState(false);
const checkAuthHome = () => {
axios.post("http://localhost:5000/api/checkauth", {}, { withCredentials: true })
.then((response) => {
setAuth(response.data.status);;
});
if (isAuth === true) {
return (<Feed />);
} else {
return (<Login />);
}
}
return (
<div className="App">
<Router>
<Routes>
<Route exact path="/" element={checkAuthHome()}/>
<Route exact path="/signup" element={<Signup />}/>
<Route exact path="/users/:id" element={<UserProfile />}/>
</Routes>
</Router>
</div>
);
}
export default App;
uj5u.com熱心網友回復:
您不得在組件渲染中進行資料提取。嘗試使用useEffect:
function App() {
const [isAuth, setAuth] = useState(false);
useEffect(()=>{
axios.post("http://localhost:5000/api/checkauth", {}, { withCredentials: true })
.then((response) => {
setAuth(response.data.status);;
});
}, [])
const checkAuthHome = () => {
if (isAuth === true) {
return (<Feed />);
} else {
return (<Login />);
}
}
return (
<div className="App">
<Router>
<Routes>
<Route exact path="/" element={checkAuthHome()}/>
<Route exact path="/signup" element={<Signup />}/>
<Route exact path="/users/:id" element={<UserProfile />}/>
</Routes>
</Router>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405406.html
標籤:
上一篇:如何使用正則運算式或純JavaScript從字串中洗掉所有括號及其內容并保留其他文本格式
下一篇:元素.innerText不顯示
