V
V
vaskadogana2017-02-08 11:40:59
React
vaskadogana, 2017-02-08 11:40:59

Passing state in react to an ancestor, is it possible without global storage?

I am writing in React, there is such a code

var ContentControlPage = React.createClass({
  getInitialState: function() {
    return {
      displayedTransport: TRANSPORT_INFO
      
    }

  },
  
  handleSearch: function(inputValue){
    var searchQuery = inputValue.toLowerCase();
    var newelement = 'false';
    var displayedTransport = TRANSPORT_INFO.filter(function(el){
      var searchValue = el.name.toLowerCase();
      return searchValue.indexOf(searchQuery) !== -1;
    });
    this.setState({
      displayedTransport: displayedTransport,
    })
  },
  fix_it: function(event){
      var displayedTransport = TRANSPORT_INFO;
      for (var i=0; i<displayedTransport.length; i++) {
        displayedTransport[i].fixed = false;
      }
      console.log(displayedTransport);
  },
  	render: function() {
  		
    return(
      <div>
          <FilterForAll updateFilterForAll={this.handleSearch}  />
          <div className="left_sidebar">
            <ul className="transport_data_container"  onClick={this.fix_it}>
              {
                this.state.displayedTransport.map(function(el){
                  return <Filtered_Data 
                      key={el.id} 
                      name={el.name} 
                      imagesrc={el.imagesrc}
                      />;
                })	
              }
            </ul>
          </div>
      </div>
    )
  }
});
в классе Filtered_Data, есть еще один класс на который нужно повесить event onClick которое нужно обрабатывать на уровне ContentControlPage, чтобы манипулировать state displayedTransport

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AlexChebanenko, 2017-02-09
@vaskadogana

Dear colleague, you need to pass a function as a prop from this component to the Filtered_Data component (let's call it, for example, handleClick), which will be called from the child component Filtered_Data as this.props.handleClick()(add parameters if necessary). handleClick should be located in the parent ContentControlPage and change its state (there will be a call this.setState()).
For some developers, this can be difficult to understand, and in a sense, this creates a "mess" and is an anti-pattern. If such a trick in your project is not a single one, I recommend looking towards the Flux or Redux architectures.

D
davidnum95, 2017-02-08
@davidnum95

Some kind of tin, of course, through props you can.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question