2015-06-20 73 views
0

我想爲我的搜索結果中映射的每個項目發出超級請求。要檢查項目ID是否在數組中:React - 每個映射項目的超級請求

我有這些方法;一個用來繪製結果,另一個用superagent獲取:

renderResultNodes: function() { 
    if(!this.props.results) return; 

    return this.props.results.map(function (result) { 
     // fire off request here? 
     // show tick icon if id exists 
     var showIcon = this.isSchool(school.id) ? <i className="icon item-icon-right ion-checkmark-circled"></i> : ''; 

     return (
      <a className="item item-icon-right" key={result.id} href="#" 
       data-school-id={result.id} 
       data-school-name={result.school_name} 
       onClick={this.selectSchool} 
       > 
       <h2>{result.school_name}</h2> 
       <p>{result.s_address1}</p> 
       {showIcon} 
      </a> 
     ); 
    }.bind(this)); 
}, 

// check id exists in json 
isSchool: function (schoolId){ 
    var url = OsaApiService.buildRequestUrl('home', [schoolId]); 

    fetch(url) 
     .then(function (response) { 
      return response.json(); 
     }).then(function (data) { 
      console.log(data); 
     }.bind(this)).catch(function (ex) { 
      console.log(ex); 
     }); 
}, 

任何人都可以建議這是否是最好的方法嗎?以及我應該如何去做呢?

感謝

+0

個人而言,我會重新考慮你的方法。在渲染之前構建數據。 –

回答

1

你可以使用其他組件的結果,以利用其生命週期和狀態:

var Result = React.createClass({ 
    getInitialState() { 
    return { 
     isSchool: false 
    } 
    }, 
    componentDidMount() { 
    var url = OsaApiService.buildRequestUrl('home', [this.props.id]) 
    fetch(url) 
     .then(response => response.json()) 
     .then(data => this.setState({isSchool: /* whatever you need from data */})) 
     .catch(err => console.log(err)) 
    }, 
    render() { 
    return <a className="item item-icon-right" onClick={this.props.onClick}> 
     <h2>{this.props.school_name}</h2> 
     <p>{this.props.s_address1}</p> 
     {this.state.isSchool && <i className="icon item-icon-right ion-checkmark-circled"></i>} 
    </a> 
    } 
}) 

...

renderResultNodes: function() { 
     if(!this.props.results) return; 

     return this.props.results.map(function(result) { 
      return <Result key={result.id} onClick={this.selectSchool} {...result}/> 
     }, this) 
    },