首页 > 解决方案 > 将道具传递给 NavBar 不会更新组件

问题描述

我正在建立一个广告网站。我建立了一个注册系统,它工作得很好,但由于某种原因,我无法根据发生的事件更新 NavBar。例如,我想将名为“LOGIN/REGISTER”的 NavLink 替换为“LOGGED IN”。我已经将 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 中,我可以这样做:

简介.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>
  )}}

但是当我在菜单组件中尝试它时,我无法管理它来相应地更新:

导航栏.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>
    );
  }
}

标签: javascriptreactjsparameter-passingnavbar

解决方案


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

推荐阅读