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

时间:2018-12-12 14:46:56

标签: javascript reactjs parameter-passing navbar

我正在建立一个广告网站。我建立了一个注册系统,可以很好地运行,但是由于某种原因,我无法根据已发生的事件更新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>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

反应只会在响应新状态或新道具时更新。您正在操纵不会导致组件重新渲染的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>
    );
  }