道具变更时,状态不会更新

时间:2020-08-07 07:54:39

标签: reactjs

几天来我一直在学习“反应文档”的反应,今天我陷入了麻烦。链接到文档:https://reactjs.org/docs/conditional-rendering.html#element-variables

锻炼是指单击按钮时文本将改变。在文档中,他们使用函数来完成此操作,并且效果很好,但是我尝试了使用类。

问题在于道具更改时状态不会更新,只有其初始值。自2个小时以来,我一直在苦苦挣扎,却找不到解决方案。我是React的新手,所以请原谅。

代码:

class UserGreeting extends React.Component {
  render() {
    return (
      <h1>Welcome back!</h1>
    );
  }
}

class GuestGreeting extends React.Component {
  render() {
    return (
      <h1>Please sign up!</h1>
    );
  }
}

class Greeting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isLoggedIn: this.props.isLoggedIn};
  }

  render() {
    let isLoggedIn = this.state.isLoggedIn;

    if (isLoggedIn) {
      return <UserGreeting />;
    }
    return <GuestGreeting />;
  }
}

class LoginButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {onClick: this.props.onClick};
  }

  render() {
    return (
      <button onClick={this.state.onClick}>Login</button>
    );
  }
}

class LogoutButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {onClick: this.props.onClick};
  }

  render() {
    return (
      <button onClick={this.state.onClick}>Logout</button>
    );
  }
}

class LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isLoggedIn: true};
  }

  handleLoginClick = () => {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick = () => {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;
    if (isLoggedIn) { 
      button = <LogoutButton onClick={this.handleLogoutClick} />;    
    } else {      
      button = <LoginButton onClick={this.handleLoginClick} />;    
    }
    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
          {button}     
       </div>
    );
  }
}


ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

1 个答案:

答案 0 :(得分:1)

您将答案存储在构造函数内部Greeting组件中的状态中。构造函数只会在安装组件处被调用一次。

使用以下代码更改您的Greeting组件**

class Greeting extends React.Component {
  render() {
    let isLoggedIn = this.props.isLoggedIn;
    if (isLoggedIn) {
      return <UserGreeting />;
    }
    return <GuestGreeting />;
  }
}