簡體   English   中英

將道具傳遞給NavBar不會更新組件

[英]Passing props to NavBar doesn't update component

我正在建立一個廣告網站。 我建立了一個注冊系統,可以很好地運行,但是由於某種原因,我無法根據已發生的事件更新NavBar。 例如,我想用“ LOGGED IN”替換名為“ LOGIN / REGISTER”的NavLink。 我已經將User.ID的道具從父組件(App.js)傳遞到其他組件中,沒有任何問題,但是無法對NavBar做到這一點。 如果我嘗試console.log-它會說未定義。 我將放置一些代碼來證明它在哪里工作,在哪里不工作:

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;

例如在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>
  )}}

但是,當我在菜單組件中嘗試使用它時,我無法管理它進行相應的更新:

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只會在響應新狀態或新道具時進行更新。 您正在操縱不會導致組件重新渲染的cookie。 這是一個解決方案:

在您的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
    });
}

您的渲染將變為:

 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