我正在尝试在 react 中测试函数调用,但 app.js 函数在严格模式下被多次调用。
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
应用程序.js
import React from "react";
import "./App.css";
import Auth from "./Auth";
import { Route, Routes, BrowserRouter } from "react-router-dom";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Auth />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Auth.js
import React, { useState, useRef } from "react";
import "./App.css";
import CheckCurrentUser from "./CheckCurrentUser";
let counter = 0;
let currentState;
function Auth() {
const [loginState, setLoginState] = useState(false);
const CurrentAuthenticatedUser = useRef(undefined);
const loading = useRef(false);
async function checkLoginState() {
if (!loading.current) {
console.log(loading.current);
loading.current = true;
console.log(loading.current);
counter += 1;
console.log("before the await function : " + counter);
if (!CurrentAuthenticatedUser.current) {
console.log("counter value inside the if is :" + counter);
console.log(
"current authenticated user is :" + CurrentAuthenticatedUser.current
);
CurrentAuthenticatedUser.current = await CheckCurrentUser();
console.log(loading.current);
setLoginState(CurrentAuthenticatedUser.current);
loading.current = false;
}
}
console.log("after the await function : " + counter);
}
function loadingCheckLoginState() {
checkLoginState();
loading.current = true;
}
console.log("executing before");
currentState = loading.current
? console.log("loading is on")
: loadingCheckLoginState();
console.log("executing after");
return <h1>Open Points</h1>;
}
export default Auth;
CheckCurrentUser.js
function CheckCurrentUser() {
try {
console.log("inside check current user document try block");
fetch(`https://jsonplaceholder.typicode.com/posts`).then((response) =>
console.log(response)
);
return true;
} catch (error) {
console.log("no logged in user - inside catch block");
return null;
}
}
export default CheckCurrentUser;
在控制台中,我 在 Firefox 浏览器中得到以下控制台截图
我的问题是:
- 为什么 App.js 会被执行两次?
- 似乎第二次执行它,它忽略了前一个状态的结果。
我正在使用react 18。
先感谢您。问候古拉布