React React setState在第一次尝试时不会更新

时间:2020-02-18 08:41:11

标签: javascript reactjs

我必须在相同的类组件上有条件地显示div。但是状态更改仅从第二次单击开始更新。

这是我的代码

 constructor(props) {
    super(props);
    this.state = {
        openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
}

setState

    handleOpenSignIn() {
       this.setState({ openSignIn: true });
    }

如果'openSignIn'为true,我必须显示一个元素

<button className="nav-link px-4 border rounded-sm whiteBtn" onClick={() => this.handleOpenSignIn()}>Login</button>

{this.state.openSignIn &&
    <div>Show</div>
}

显示的div仅在按钮上单击两次。 在React js中是非常新的。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
  }

  handleOpenSignIn() {
    this.setState({
      openSignIn: true
    });
  }

  render() {
    return (
      <div>
        <button
          className="nav-link px-4 border rounded-sm whiteBtn"
          onClick={() => this.handleOpenSignIn()}
        >
          Login
        </button>
        {this.state.openSignIn && <div>Show</div>}
      </div>
    );
  }
}

    
 ReactDOM.render(<App/>, 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" />

2 个答案:

答案 0 :(得分:0)


import React from 'react';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
  }

  handleOpenSignIn() {
    this.setState(prevState => ({
      openSignIn: !prevState.openSignIn
    }));
  }

  render() {
    return (
      <div>
        <button
          className="nav-link px-4 border rounded-sm whiteBtn"
          onClick={() => this.handleOpenSignIn()}
        >
          Login
        </button>
        {this.state.openSignIn && <div>Show</div>}
      </div>
    );
  }
}

如果要切换而不只是显示,可以使用上面的代码。 您不应像在代码段中所做的那样更改布尔状态。

答案 1 :(得分:0)

但是它确实可以正常工作。

Open code sandbox to run your code