0

当我的本地存储不为空时,我想更改我的菜单,但我很难使用道具来做到这一点。

我的组件菜单上有带有条件的菜单,并且我的组件应用程序带有导航:

组件菜单

function Menu(props) {
  const showMenu = (props) => {
    if (props.isLoggedIn === true) {
      return (
        <div className="ContainerMenu">
          <ul className="Menu">
            <Link to="/Home">
              {" "}
              <li>who am i</li>
            </Link>
            <li>some of my products</li>
            <Link to="/contact">
              <li>Contact me</li>
            </Link>
            <Link to="/">
              <li className="connexion">Connexion</li>
            </Link>
          </ul>
        </div>
      );
    } else {
      return (
        <div className="ContainerMenu">
          <ul className="Menu">
            <Link to="/">
              <li className="connexion">Connexion</li>
            </Link>
          </ul>
        </div>
      );
    }
  };

  useEffect(() => {
    showMenu();
  }, []);

  return <div>{showMenu()}</div>;
}

export default Menu;

当我的本地存储上有我的电子邮件时,我想将我的登录设置为 true。我很想用道具做到这一点,但我想我错过了什么?

function App(props) {
  const [isLoggedIn, setLoggedIn] = useState(false);

  const ifLoggedIn = () => {
    if (localStorage.getItem("connexion")) {
      setLoggedIn(true);
    }
  };

  useEffect(() => {
    ifLoggedIn();
    console.log(isLoggedIn);
  });

  return (
    <Router>
      <div>
        <Menu isLoggedIn={ifLoggedIn} />
        <Switch>
          <Route path="/contact" component={MeContacter} />
          <Route path="/Home" component={Home} />
          <Route path="/" component={Connexion} />
        </Switch>
        <Footer />
      </div>
    </Router>
  );
}

export default App;

4

1 回答 1

1

你有一个错字

代替:

 <Menu isLoggedIn={ifLoggedIn} />

经过 :

 <Menu isLoggedIn={isLoggedIn} />

您的菜单组件结构不合理:

function Menu(props) {
  const showMenu = () => {
    if (props.isLoggedIn === true) {
      return (
        <div className="ContainerMenu">
          <ul className="Menu">
            <Link to="/Home">
              {" "}
              <li>who am i</li>
            </Link>
            <li>some of my products</li>
            <Link to="/contact">
              <li>Contact me</li>
            </Link>
            <Link to="/">
              <li className="connexion">Connexion</li>
            </Link>
          </ul>
        </div>
      );
    } else {
      return (
        <div className="ContainerMenu">
          <ul className="Menu">
            <Link to="/">
              <li className="connexion">Connexion</li>
            </Link>
          </ul>
        </div>
      );
    }
  };

  return <div>{showMenu()}</div>;
}

export default Menu;
于 2021-10-04T08:54:38.073 回答