多次执行文件导致react js 中的多个服务器调用

IT技术 reactjs
2022-08-01 02:03:49

我正在尝试在 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 浏览器中得到以下控制台截图

我的问题是:

  1. 为什么 App.js 会被执行两次?
  2. 似乎第二次执行它,它忽略了前一个状态的结果。

我正在使用react 18。

先感谢您。问候古拉布

1个回答

我没有分析你的代码来寻找答案,但最有可能的答案是 React 18 和严格模式是双重安装组件。您可以在此处了解更多信息