2

我在 Header 中创建了 4 个链接。主页、待办事项、登录、注销。这是我想要的东西

  1. Home、Todos 和 Logout 链接仅在用户登录时可用。

我已经使用 sessionStorage 来检查用户是否登录并且它工作正常。问题是登录后我需要刷新网页以取消隐藏主页、待办事项和注销。如何在不刷新网页的情况下取消隐藏它们。意味着在我登录后我仍然需要刷新我的页面,我不喜欢那样。这是我的代码示例

class AuthenticationService {
      successLogin(username, password) {
        console.log("Register Successfull");
        sessionStorage.setItem("authenticatedUser", username);
      }
      successLogout() {
        sessionStorage.removeItem("authenticatedUser");
      }
      isUserLoggedIn() {
        let user = sessionStorage.getItem("authenticatedUser");
        if (user === null) {
          return false;
        } else {
          return true;
        }
      }
    }
    export default new AuthenticationService();

页眉.js

import React, { Component } from "react";
import { Link } from "react-router-dom";
import AuthenticationService from "../Security/AuthenticationService";

class Header extends Component {
  render() {
    const isUserLoggedIn = AuthenticationService.isUserLoggedIn();
    console.log(isUserLoggedIn);
    return (
      <header>
        <nav className="navbar navbar-expand-md navbar-dark bg-dark">
          <ul className="navbar-nav">
            {isUserLoggedIn && (
              <li>
                <Link className="nav-link" to="/welcome/jarvis">
                  HOME
                </Link>
              </li>
            )}
            {isUserLoggedIn && (
              <li>
                <Link className="nav-link" to="/todos">
                  Todos
                </Link>
              </li>
            )}
          </ul>
          <ul className="navbar-nav navbar-collapse justify-content-end">
            {!isUserLoggedIn && (
              <li>
                <Link className="nav-link" to="/login">
                  Login
                </Link>
              </li>
            )}
            {isUserLoggedIn && (
              <li>
                <Link
                  className="nav-link"
                  to="/logout"
                  onClick={AuthenticationService.successLogout}
                >
                  Logout
                </Link>
              </li>
            )}
          </ul>
        </nav>
      </header>
    );
  }
}

export default Header;

登录成功

loginResponse = () => {
    if (this.state.username === "jarvis" && this.state.password === "jarvis") {
      this.setState({ loginStatus: true });
      AuthenticationService.successLogin(
        this.state.username,
        this.state.password
      );
      this.props.history.push(`/welcome/${this.state.username}`);
    } else {
      this.setState({ loginStatus: false });
    }
  };
4

1 回答 1

1

通过读取状态设置isUserLoggedIn,不要直接访问AuthenticationService.

于 2020-07-27T10:24:00.730 回答