2017-01-19 129 views
0

我有這樣的情況,我的反應路由器:加載狀態反應

root.js

<Route path="job-opportunity" component={Opportunity} > 
    <Route path=":opportunitySlug" /> 
</Route> 

當我打開domain.com/job-opportunity一切工作正常 但是,當我打兒童路線domain.com/job-opportunity/some-slug

它不加載我在兒童組件中使用的機會組件的一些構造函數狀態。

讓我告訴你我的機會組件:

class Opportunity extends React.Component{ 
    constructor(props){ 
     super(props); 

     this.loadOpportunities = this.loadOpportunities.bind(this); 

     this.state = { 
      'opportunities' : [] 
     }; 
     this.loadOpportunities(); 
    } 
    loadOpportunities(){ 
     $.get($('.api_router_load_opportunities').val(), function(data){ 
      this.setState({'opportunities' : data}); 
     }.bind(this)); 
    } 
    render() { 
     return (
      <div> 
       <h1>Layout!</h1> 
       <Content 
        opportunities={this.state.opportunities} 
        loggedUser={this.props.loggedUser} 
        opportunitySlug={this.props.params.opportunitySlug} 
        /> 
      </div> 
     ) 
    } 
} 

function Content(props){ 
    const opportunitySlug = props.opportunitySlug; 
    if(opportunitySlug){ 
     return <SingleOpportunity 
      opportunities={props.opportunities} 
      loggedUser={props.loggedUser} 
      opportunitySlug={opportunitySlug} 
      />; 
    }else{ 
     return <ListOpportunity 
      opportunities={props.opportunities} 
      loggedUser={props.loggedUser} 
      />; 
    } 
} 

出口默認機會;

domain.com/job-opportunity/some-slug

但當:

基本上當我打domain.com/job-opportunity然後在瀏覽器中的一切鏈接導航,即使在這條線路工作正常我直接打在瀏覽器domain.com/job-opportunity/some-slug

它brokes因爲我在SingleOpportunity this.props.opportunities渲染[this.props.opportunitySlug]。名稱

回答

0

我找到了一些解決方案:

if(this.props.opportunities.length != 0){ 
      const opportunity = this.props.opportunities[this.props.opportunitySlug]; 
      return (
       <div key={this.props.opportunitySlug}> 
        <p><strong>Name:</strong> {opportunity.name}</p> 
        <p><strong>Description:</strong> {opportunity.description}</p> 
       </div> 
      ); 
     }else{ 
      return null; 
     } 

如果您在初始加載之後使用了一些道具或狀態,它會渲染多次,並且在最後一次渲染時會加載您的道具或狀態!所以你需要處理你通過檢查來呈現函數是你的狀態還是道具準備就緒。