简体   繁体   English

将道具传递给NavBar不会更新组件

[英]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. 我建立了一个注册系统,可以很好地运行,但是由于某种原因,我无法根据已发生的事件更新NavBar。 For example, I want to replace the NavLink called "LOGIN/REGISTER" with "LOGGED IN". 例如,我想用“ LOGGED IN”替换名为“ LOGIN / REGISTER”的NavLink。 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. 我已经将User.ID的道具从父组件(App.js)传递到其他组件中,没有任何问题,但是无法对NavBar做到这一点。 If I try a console.log - it would say undefined. 如果我尝试console.log-它会说未定义。 I am going to put a couple of codes demonstrating where it works and where it does not: 我将放置一些代码来证明它在哪里工作,在哪里不工作:

APP.JS 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中,我可以这样做:

PROFILE.JSX 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 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. React只会在响应新状态或新道具时进行更新。 You are manipulating a cookie which can't cause a component re-render. 您正在操纵不会导致组件重新渲染的cookie。 Here's a solution: 这是一个解决方案:

In your App component change the Log methods to: 在您的App组件中,将Log方法更改为:

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>
    );
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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