简体   繁体   中英

Passing props to NavBar doesn't update component

I am building an ad website. I built a registration system, which works perfectly fine, but for some reason I can't update the NavBar based on the event that has happened. For example, I want to replace the NavLink called "LOGIN/REGISTER" with "LOGGED IN". I have passed the props of the User.ID from the parent component (App.js) into the other components without any problem, but cannot do this for the NavBar. If I try a console.log - it would say undefined. I am going to put a couple of codes demonstrating where it works and where it does not:

APP.JS

*imports, which I am skipping*

const cookies = new Cookies();

class App extends Component {

  constructor(){
    super();
    this.state = {
    }
    this.LogUser = this.LogUser.bind(this);
    this.LogoutUser = this.LogoutUser.bind(this);
  }

  LogUser(User, ID){
    cookies.set('User', User, { path: '/' });
    cookies.set('UserID', ID,{ path: '/'});
  }
  LogoutUser(){
    cookies.remove('User')
  }

  render() {
    return (
      <div>
      <div>

      //MENU <- WHERE I CAN'T PASS THE PROPS OF USER AND USERID

        <Menu render={(props) => <Menu {...props} User={cookies.get('User')} ID={cookies.get('UserID')} LogOutUser={this.LogoutUser} />}/>

      </div>

        <Router history = {history} >
          <div>

          //I have removed all other routes as they are not needed, but here is an example, in which the passing of props works

            <Route path = "/Profile" render={(props) => <Profile {...props} User={cookies.get('User')} ID={cookies.get('UserID')} LogOutUser={this.LogoutUser} />}/>

          </div>
        </Router>
      </div>
    );
  }
}

export default App;

And for example in Profile.jsx, I can do that:

PROFILE.JSX

export default class Profile extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      LoggedUser: '',
      UserID: '',
    };
    this.LogOutClick = this.LogOutClick.bind(this);
  }

  LogOutClick(){

    this.props.LogOutUser(); 
    history.push('/Logout');
  } 


  componentDidMount(){

    if (this.props.User !== undefined)
    {
    this.setState({LoggedUser: this.props.User, UserID: this.props.ID})
    }
    else
    {
      history.push('/Login');
    }
  }

  render() {
    return (
      <div>
       Hello, {this.props.User}!
      <div>
  )}}

But when I try it in the Menu component, I can't manage it to update accordingly:

NAVBAR.JSX

export default class Menu extends React.Component {
  constructor(props) {
    super(props);


    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false,
      Title: '',
    };
  }
  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }


   //here I tried to put something similar to the ComponentDidMount() in Profile.jsx, but it didn't work.

componentDidMount(){

    if (this.props.User !== undefined)
    {
    this.setState({LoggedUser: this.props.User, UserID: this.props.ID})
    this.setState({Title: "LOGGED IN"})
    }
    else
    {
      this.setState({Title: "LOGIN/REGISTER"})
    }
  }


  render() {
    console.log(this.state.User)
    console.log(this.state.ID)
    return (
      <div>
        <Navbar color="light" light expand="md">
          <NavbarBrand href="/"><img src={require('./images/home.png')} width = "25px" height = "25px"/></NavbarBrand>
          <NavbarToggler onClick={this.toggle} />
          <Collapse isOpen={this.state.isOpen} navbar>
            <Nav className="ml-auto1" navbar>
              <NavItem>
                <NavLink href="/Ads"><b>ADS</b></NavLink>
              </NavItem>
              <NavItem>
                <NavLink href="/Profile"><b>YOUR PROFILE</b></NavLink>
              </NavItem>
              <NavItem>
                                           //What I want to update
                <NavLink href="/Login"><b>{this.state.Title}</b></NavLink>
              </NavItem>
            </Nav>
          </Collapse>
        </Navbar>
      </div>
    );
  }
}

React will only update in response to a new state or new props. You are manipulating a cookie which can't cause a component re-render. Here's a solution:

In your App component change the Log methods to:

constructor(){
    super();
    this.state ={
        currentUserId: cookies.get('UserID'),
        currentUser: cookies.get('User')
    };
    this.LogUser = this.LogUser.bind(this);
    this.LogoutUser = this.LogoutUser.bind(this);
}
LogUser(User, ID){
    cookies.set('User', User, { path: '/' });
    cookies.set('UserID', ID,{ path: '/'});
    this.setState({
        currentUserId: ID,
        currentUser: User
    });
}
LogoutUser(){
    cookies.remove('User');
    this.setState({
        currentUserId: null,
        currentUser: null
    });
}

And your render will become:

 render() {
    return (
      <div>
      <div>

        <Menu render={(props) => <Menu {...props} User={this.state.currentUser} ID={this.state.currentUserId} LogOutUser={this.LogoutUser} />}/>

      </div>

        <Router history = {history} >
          <div>

          //I have removed all other routes as they are not needed, but here is an example, in which the passing of props works

            <Route path = "/Profile" render={(props) => <Profile {...props} User={this.state.currentUser} ID={this.state.currentUserId} LogOutUser={this.LogoutUser} />}/>

          </div>
        </Router>
      </div>
    );
  }

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