提问者:小点点

如何同步React中不同组件的身份验证状态?


我在这种情况下陷了很久了。 我当时正在做React的一个应用程序,在我的主页上,我有一个导航栏和另一个组件。 这里我要做的是当我登录/注销时,我的导航栏和我的其他组件将同步改变。 但实际上,当我在导航栏中单击Login/Log out时,只有导航栏改变了,其他组件保持不变,直到我重新加载页面。 如何使登录状态全局化? 以便每个组件都能同步变化? 我真的很感谢你的帮助!

mainpage.js

const MainPage = () => {
  const [isAuth, setAuth] = React.useState(
    window.localStorage.getItem("isAuth")
  );
  const handleLogOut = () => {
    setAuth(false);
    window.dataLayer.push({
      event: "Log Out",
      user: "Anonymous",
      timezone: "Chicago",
    });
    window.localStorage.clear();
    window.alert("You have succesfully logged out!");
  };
  return (
    <div>
      {/* Navigation bar */}
      <Container
        isAuth={isAuth}
        currentPage="Main"
        onLogin={() => {
          setAuth(true);
        }}
        onLogOut={handleLogOut}
      />

      {/* Body */}

      <CardAlign>
        {food.map((foodItem) => (
          <Card foodItem={foodItem} key={`${foodItem.id}`} isAuth={isAuth} />
        ))}
      </CardAlign>

      {/* Buttons */}
      <Buttons isAuth={isAuth} currentPage="Main" />
    </div>
  );
};

isauthsetauth是我用来定义登录状态的挂钩。 正如您在这里看到的,当容器中发生更改时,iAuth没有在按钮中同步更新

container.js

const Container = ({ isAuth, currentPage, onLogin, onLogOut }) => {
  return (
    <Header>
      <NavbarDiv>
        {!isAuth && <Login label="Login" onLogin={onLogin} />}
        {isAuth && <LogOut label="Log Out" onLogOut={onLogOut} />}
        {isAuth && <ChangeUser />}
        {isAuth && currentPage !== "Cart" && <Cart />}
        {isAuth && currentPage !== "Profile" && <Profile />}
      </NavbarDiv>
    </Header>
  );
};

container.js是我的导航栏,运行正常。

我真的真的很感激你的帮助! 请告诉我问题出在哪里,我该如何解决它! 谢谢你抽出时间!


共2个答案

匿名用户

下面是一个工作示例:

null

const Container = ({ isAuth, onLogin, onLogOut }) => {
  //using isAuth, onLogin and onLogout from props
  return isAuth ? (
    <button onClick={onLogOut}>log out</button>
  ) : (
    <button onClick={onLogin}>log in</button>
  );
};
const Buttons = ({ isAuth }) => {
  return (
    <h4>buttons: {isAuth ? 'logged in' : 'logged out'}</h4>
  );
};
const App = () => {
  const [isAuth, setAuth] = React.useState(false);
  return (
    <div>
      <Container
        isAuth={isAuth}
        currentPage="Main"
        onLogin={() => {
          setAuth(true);
        }}
        onLogOut={() => setAuth(false)}
      />
      <Buttons isAuth={isAuth} currentPage="Main" />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

匿名用户

您应该使用util.js文件来处理登录时的所有操作& 注销时,您应该导出一个函数来检查登录状态,如果您使用内部状态来处理这一点,那么您将需要将此状态作为一个道具深入传递给每个子项。

您应该使用全局状态处理程序作为redux。 或者使用PassportJS或Iron-Session。