简体   繁体   中英

setState not working in ReactJS GET method

I've been trying to make a navbar for my website that handles log in and logout authentication. To show a log in or logout button based on if the user is either. I have sucessfully retrieved the data I need but I am having trouble rendering and saving it in my Navbar component, it looks like this:

import React from 'react';

class Navbar extends React.Component {
  constructor(props){
  super(props)
this.state = { loggedin: ''}
this.isLoggedIn = this.isLoggedIn.bind(this)
  }


  componentDidMount(){
fetch('/user-status', {method: 'GET'}).then(res => res.json()).then(data =>{
  this.setState({loggedin: data})
});

  }

  isLoggedIn(){
fetch('/user-status',{ method: 'GET'})
.then(function (response) {
  return response.json();
  }).then(function (textie) {
this.setState({loggedin: textie})
return textie;
  });

}



  render() {
if(this.isLoggedIn == 'true'){
return(
  <a className="nav-item nav-link" href="/logout">Logout</a>
);
 }

return (
 <nav className="navbar navbar-expand-lg navbar-dark bg-primary">
   <a className="navbar-brand" href="#">Navbar</a>
   <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
     <span className="navbar-toggler-icon"></span>
   </button>
   <div className="collapse navbar-collapse" id="navbarNavAltMarkup">
   <div className="navbar-nav">
     <a className="nav-item nav-link active" href="#">Home <span className="sr-only">(current)</span></a>
     <a className="nav-item nav-link" href="/about">About</a>
     <a className="nav-item nav-link" href="/signin">Sign in/Sign Up</a>
     <a className="nav-item nav-link" href="/profile">My Profile</a>
     <a className="nav-item nav-link" href="/leaderboard">Top Forecasts</a>
    
   </div>
   </div>
 </nav>
    );

  }
}

export default Navbar;

The /user-status method gets whether or not the user is logged in from Flask backend, and returns either true or false. I try to save it once it changes in isLoggedIn, but I get the error cannot 'setState' on undefined. Also, when it returns textie from isLoggedIn, it returns the statement 'bound isLoggedIn' instead of true or false, and I'm not sure why.

I try to say in the render part that if the loggedin variable is true, there will be a Navbar option to logout, but if there isnt, there will be a navbar option to log in. Any thoughts why this isn't working and this error keeps popping up? I guess what I'd like to know is how to save a fetched data into a react component.

In this line if(this.isLoggedIn == 'true') you are checking if the function isLoggedIn in the this scope is equals to true, but you actually should call to this.state.isloggedIn == 'true' I think.

Try this:

class Navbar extends React.Component {
  state = { loggedin: '' };

  componentDidMount() {
    this.isLoggedIn();
  }

  isLoggedIn = () => {
    fetch('/user-status')
      .then((res) => res.json())
      .then((data) => this.setState({ loggedin: data }));
  };

  render() {
    if (this.state.loggedin == 'true') {
      return (
        <a className='nav-item nav-link' href='/logout'>
          Logout
        </a>
      );
    }

    return (
      <nav className='navbar navbar-expand-lg navbar-dark bg-primary'>
        <a className='navbar-brand' href='#'>
          Navbar
        </a>
        <button
          className='navbar-toggler'
          type='button'
          data-toggle='collapse'
          data-target='#navbarNavAltMarkup'
          aria-controls='navbarNavAltMarkup'
          aria-expanded='false'
          aria-label='Toggle navigation'
        >
          <span className='navbar-toggler-icon'></span>
        </button>
        <div className='collapse navbar-collapse' id='navbarNavAltMarkup'>
          <div className='navbar-nav'>
            <a className='nav-item nav-link active' href='#'>
              Home <span className='sr-only'>(current)</span>
            </a>
            <a className='nav-item nav-link' href='/about'>
              About
            </a>
            <a className='nav-item nav-link' href='/signin'>
              Sign in/Sign Up
            </a>
            <a className='nav-item nav-link' href='/profile'>
              My Profile
            </a>
            <a className='nav-item nav-link' href='/leaderboard'>
              Top Forecasts
            </a>
          </div>
        </div>
      </nav>
    );
  }
}

export default Navbar;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM