简体   繁体   中英

Changing a Parent's State in React.js

So I have a big analytics page. At the top, there are some form elements to choose what you'd like to see the report about.

Below that are some graphs and tables.

So I have the hierarchy set up like this

Page
    Otherstuff1
    Report
        Setting1 
        Setting2
        Graph1
        Graph2
        Table
    Otherstuff2

I think the state of this report should be held in the Report component, as it's the lowest component that contains everything that needs access to this state.

So how can I update the state of Report when there is a change in Setting1 ?

Here's a simplified version of my code, relevant to the question.

var Report = React.createClass({

  getInitialState: function() {
    return {
      dateRange: "not changed",
    }
  },

  changeDateRange: function(event) {
    console.log("changed");
    this.setState({dateRange: "changed"});
  },

  render: function() {
    return (
      <div>
        <ReportDateRange change={this.changeDateRange}/>
        {this.state.range}
      </div>
    );
  }

});

var ReportDateRange = React.createClass({
  render: function() {
    return (
      <select className="form-control" id="historicalRange"
          onChange={this.props.change}>
        <option value="yesterday">Yesterday</option>
        <option value="week">Last week</option>
        <option value="fortnight">Last fortnight</option>
        <option value="month" selected>This month</option>
      </select>
    )
  }
});

This code runs, and it does log in the console that something changed, but it does not update the state of Report . I think it might be updating the state of ReportDateRange instead.

The control flow looks right to me.

I think what you've got wrong is how you've referenced the state variable.

In your render() function you reference this.state.range but elsewhere that variable is dateRange not range .

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