简体   繁体   中英

State in React.js

I am new in React.js. I have below code, where the variable modalOpen value is not changing.

constructor(props) {
    super(props);

    this.state = {
      modalOpen: false,
    };

    this.view = this.view.bind(this);
}
view() {
    this.setState({ modalOpen: true });

    alert(this.state.modalOpen)
}
render() {
    return (
        <button className="mini ui button" onClick={this.view}>
            <i className="user icon"></i>
            View
        </button>
    )
}

How can I change the value ?

Your code is correct you may need to put the alert in call back of setState or in render

  constructor(props) {
    super(props);

    this.state = {
      modalOpen: false,
    };

    this.view = this.view.bind(this);
  }
  view() {
    this.setState({ modalOpen: true }, ()=>{
      alert(this.state.modalOpen)
    });

  }
  render() {
    return (
      <div>
      <button className="mini ui button" onClick={this.view}>
        <i className="user icon"></i>
        View
        </button>
      {this.state.modalOpen ? 'true' : 'false'}
        </div>
    )
  }
}

from React Docs :

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

setState(updater, callback)

A. If you want to do something with the prev state, you'd better pass a function as a updater to setState .

this.setState((prevState, props) => {
  return {counter: prevState.counter + props.step};
});

B. For your case, after updating the state and want to call the callback function, you will need the callback for the setState , for example:

view() {
  this.setState({
    modalOpen: true
  }, () => {
    alert(this.state.modalOpen)
  });
}

Because setState is asynchronous。 The reason react does that is to improve performance. It's like when you add a listener to window.resize event, you don't want your listener to be called every time resize event is emitted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM