简体   繁体   中英

State value not updating reactjs

class RaisablePaper extends Component {
        constructor(props) {
            super();
            this.state = {
                state1: "state1",
                openNow: props.boxOpen,

            };
        }
}

I am trying to send value to this class by doing <RaisablePaper boxOpen={this.state.dOpen}/> . But whenever the dOpen gets changed it does not seem to update the openNow . Help would very much appreciated.

You are setting the state before mounting the component in the constructor , which will not be fired again when the props change. For that you can use React's componentWillReceiveProps , which will be called when new props are sent to the component.

class RaisablePaper extends Component {
  constructor(props) {
    super();
    this.state = {
      state1: "state1",
      openNow: props.boxOpen
    };
  }
  componentWillReceiveProps(props) {
    this.setState({
      openNow: props.boxOpen
    });
  }
}

It would be simpler to use the props directly instead of worrying about syncing it to your state. It's a good idea in general to rely on props as much as possible, and only involve state when absolutely necessary.

But Fabian Schultz is absolutely right -- your constructor only runs once, before the component is mounted, so you'll never receive the subsequent updates if the component is relying on state which is initialized during construction.


I'm just imagining how you're using the boxOpen state to show an example; you can follow the same general idea with whatever your render method is doing.

class RaisablePaper extends Component {
  render() {
    return (
      <div className={this.props.boxOpen ? 'is-open' : ''}>
        Here's some content...
      </div>
    );
  }
}

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