条件检查无法在React组件中按预期方式工作

时间:2019-02-05 17:49:57

标签: reactjs apollo-client react-cookie

我正在根据身份验证状态设计标题以显示登录和注销按钮,并且我使用React-cookie存储身份验证状态

组件代码

import React, { Component } from "react";
import { Link } from "react-router-dom";
import { withCookies } from "react-cookie";

class HeaderComponent extends Component {
  renderAuthMenu = () => {
    const { cookies } = this.props;
    console.log(cookies.get("loggedIn"));
    if (cookies.get("loggedIn")) {
      return (
        <ul className="navbar-nav ml-auto" style={{ margin: "0 2em" }}>
          <li className="nav-item">
            <Link to="/logout">Logout</Link>
          </li>
        </ul>
      );
    } else {
      return (
        <ul className="navbar-nav ml-auto" style={{ margin: "0 2em" }}>
          <li className="nav-item">
            <Link to="/login">Login</Link>
          </li>
          <li className="nav-item" style={{ margin: "0 2em" }}>
            <Link to="/register">Signup</Link>
          </li>
        </ul>
      );
    }
  };

  render() {
    return (
      <div>
        <nav className="navbar navbar-expand-lg navbar-light bg-light">
          <Link className="navbar-brand" to="/">
            V1-WorldWide
          </Link>
          <button
            className="navbar-toggler"
            type="button"
            data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent"
            aria-expanded="false"
            aria-label="Toggle navigation"
          >
            <span className="navbar-toggler-icon" />
          </button>

          <div className="collapse navbar-collapse" id="navbarSupportedContent">
            <ul className="navbar-nav mr-auto">
              <li className="nav-item" style={{ margin: "0 2em" }}>
                <Link to="/">Products</Link>
              </li>
              <li className="nav-item" style={{ margin: "0 2em" }}>
                <Link to="/products/new">Add Product</Link>
              </li>
            </ul>

            {this.renderAuthMenu()}
          </div>
        </nav>
      </div>
    );
  }
}

export default withCookies(HeaderComponent);

请注意:-在if检查前控制台显示正确的值,但未呈现正确的条件部分 我也在使用ApolloClient,我不确定这是否重要

0 个答案:

没有答案