2016-11-08 94 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