W
W
waweca2015-08-21 23:25:24
JavaScript
waweca, 2015-08-21 23:25:24

How to get state from another component in React.js?

In general, there are two components.

var Comp1 = React.createClass({
  getInitialState: function() {
    return {
      data: []
    };
  },

  componentWillMount: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'GET',
      success: function(data) {
        this.setState({
          data: data
        });
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

  render: function() {
    return (
        <div>
          {this.state.data}
        </div>
    );
  }
});

var Comp2 = React.createClass({
  render: function() {
    return (
        <div>
          {this.state.data} // ?
        </div>
    );
  }
});

The first component makes/receives a request.
How in the second component to use the data received/caused by the first component?
Or is it correct to make a separate request for each component?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Goryachkin, 2015-08-21
@waweca

If you do not adhere to the flux architecture, then like this:

var Comp1 = React.createClass({
//code
render: function() {
    return (
        <div>
         <Comp2 data={this.state.data} />
        </div>
    );
  }
});
var Comp2 = React.createClass({
  render: function() {
    return (
        var fromOne = this.props.data;
        <div>
          {fromOne}
        </div>
    );
  }
});

And if you stick with flux-sa, then you need Dispatcher and Store. When receiving data from the server, you transfer the data to the storage using the Dispatcher, after that the storage says that the data has changed, and in the components you put a listener on the data change. And as soon as a change occurs, you take the fresh data from the storage and already do what you want with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question