2016-11-08 107 views
1

我有一個路由器和一個組件的文件。不久,代碼是這樣的:如何在React Router自動更改後更新狀態?

// define the routes for each language .. 
const InnerRoutes = (
    <Route> 
     <IndexRoute page="home" component={StaticPage}></IndexRoute> 
     <Route path="contacts" component={ContactsPage}></Route> 
     <Route path="(:page)" component={StaticPage}></Route> 
    </Route> 
); 

// define the routes for all the languages, using InnerRoutes .. 
const AllRoutes = (
    <Router history={browserHistory}> 
     <Route path='/' component={App} language="bg"> 
      {InnerRoutes} 
      <Route path="en" language="en"> 
       {InnerRoutes} 
      </Route> 
     </Route> 
    </Router> 
); 

// and render our app .. 
ReactDOM.render(
    AllRoutes, 
    document.getElementById('app') 
); 

我的問題是:我怎麼能有路由器變化時觸發App組件狀態改變了嗎? 當然 - 在應用程序狀態下有路由器參數。

(因爲目前我可以從App組件的方法componentDidUpdate採取路由器的東西,然後觸發setState改變App狀態不幸的是 - 那麼我有componentDidUpdate觸發兩次)

回答

0

我已經添加到了我的應用程序,它似乎接收路線改變時的變化。更多參考here

class App extends React.Component { 

    ... 

    getInitialState() { 
     return { 
     lang: 'en' // default 
     }; 
    } 

    componentWillReceiveProps(props) { 
     console.log('location: ', props.location.pathname); 
     var newLang = props.location.pathname.split('/').shift(); 
     if(this.state.lang !== newLang) { 
      this.setState({lang: newLang}); 
     } 
    } 

    render() { 

    const lang = this.state.lang; 

    return (
     <AboutPage language={lang} /> 
     <Support language={lang} /> 
    ); 
    } 
} 

如果這也不行,你也可以看看how two components talk to each other

+0

好了,從那裏去,但它並沒有爲我工作。因爲我在'App'組件狀態中有'language',並且當路由發生變化時 - 我想要1)App的狀態自動改變,並且2)子節點從頂層App的組件中接收新的道具。 .........正如我所見 - 現在 - 我將不得不手動改變狀態,檢查位置,在'應用程序':( –

+0

@peshohristov好吧,我已經更新了我的答案。那是什麼你的意思是嗎? – tsuz

+0

恕我直言,將newLang存儲到狀態是不必要的。 }' – mauron85

相關問題