2016-11-14 91 views
0

檢查完this react-router tutorial後,我嘗試將我在這裏學到的東西整合到我的項目中。React-Router對我的生命週期路由器感到困惑

我的情況是類似的,從教程2號,不同之處在於當用戶進入/,我希望獲取的API,並重定向到第一類的,看起來像這樣[{'category':'electronics', 'items':[{..}],..},..]

的API正在添加我的路由器看起來像這樣

import RoutaZ from 'Routes.js'; 
... 

<Router history={hashHistory}> 
<Route path="/" component={App}> 
    <IndexRedirect to={RoutaZ.state.data[0].name} /> 
    <Route path=":category" components={Container, SideNavigation} /> 
</Route> 

我Routes.js看起來像這樣

let Routes = React.createClass({ 
getInitialState() { 
    return { 
    data: null 
    } 
}, 

componentDidMount() { 
var self = this; 
fetchData().then(function(results){ 
    self.setState({data: results.data}); 
}) 
}, 

render() { 
/* want to return the the first category from api */ 
    return this.state.data[0].name 
} 
}); 

在路由器中,RoutaZ.state.data[0].name返回未定義,因爲初始狀態爲空。如果我將初始狀態設置爲[{'category':'hello',...}],它將返回hello並按照預期重定向到hello頁面。在獲取數據庫之後,我能做些什麼來重定向?

1)如何從我的當前配置中使用react-router的onEnter

2)如何以及在哪裏可以設置一個父組件到我的路由器處理所有抓取並將它作爲孩子傳遞給路由器?


編輯:這是我的應用程序,這是完成了,但我只有這個重定向問題的只是一小部分。我知道我可以使用REDX-SAGA,但是我的所有應用程序已經完成,並且必須完全重做,這是我無法承受的。

1-我試過使用onEnter,但不知道應該放在哪裏。

2-我的應用程序中的某處是從父組件獲取數據,並將其作爲道具給孩子,孩子從api接收數據。

回答

0

解決了它。當組件安裝時我必須推送結果

componentDidMount() { 
var self = this; 
fetchData().then(function(results){ 
    router.push(results.data[0].category); 
}) 
},