React if 语句总是在 re-render 阶段后导致错误条件

React if statments always results in false condition after state re-render

我在 React 中有这个组件,它将 return 'Loading' 标题、'Logged in' 标题或 'Not Logged in' 标题,具体取决于状态。

我已经创建了状态,一旦 isLoggedIn 承诺 return,它就会从 'Loading' 更新并更改为 'Logged in' 或 'Not Logged in' s 值 truefalse

然而,我的第二个 If 语句总是有条件地证明是假的,因此总是 returning 'Not Logged in' 作为标题,即使承诺 return 是真的(说用户是已登录)。

代码如下:

function UserProfileNavItem(props) {
  const [profiledLoaded, sethasLoaded] = useState(false);
  var isLoggedInLocal = false;
  isLoggedIn().then((res) => {
    if (res) {
      console.log("We are logged in");
      isLoggedInLocal = true;
    }else{
      console.log("We are not logged in");
    }
    sethasLoaded(true);
  });
  if (!profiledLoaded) {
    return (
      <h1>Loading</h1>
    );
  }
  if (!isLoggedInLocal) {
    return (
      <h1>Not Logged In</h1> // THIS IS ALWAYS SENT BACK EVEN IF isLoggedInLocal IS TRUE
);
  } else {
    return (
      <h1>Logged In</h1>  // THIS IS NEVER SENT BACK
    );
  }
}

不要认为我需要展示我的isLoggedIn承诺,但问你是否需要。

(是的,我是新来的)

var isLoggedInLocal = false; 写为状态以便反应:

function UserProfileNavItem(props) {
  const [profiledLoaded, sethasLoaded] = useState(false);
const [isLoggedInLocal , setIsLoggedInLocal ] = useState(false);
 
  isLoggedIn().then((res) => {
    if (res) {
      console.log("We are logged in");
      setIsLoggedInLocal(true);
    }else{
      console.log("We are not logged in");
    }
    sethasLoaded(true);
  });
  if (!profiledLoaded) {
    return (
      <h1>Loading</h1>
    );
  }
  if (!isLoggedInLocal) {
    return (
      <h1>Not Logged In</h1> IS TRUE
);
  } else {
    return (
      <h1>Logged In</h1> 
    );
  }
}