【问题标题】:How to update state after React Router changes automatically?React Router 自动更改后如何更新状态?
【发布时间】:2017-03-22 07:23:11
【问题描述】:

我有一个包含路由器和组件的文件。很快,代码是这样的:

// 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 两次。)

【问题讨论】:

    标签: reactjs react-router state


    【解决方案1】:

    我已将此添加到我的应用程序中,并且它似乎会在路线更改时收到更改。更多参考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

    【讨论】:

    • 好的,它从那里开始,但它对我不起作用。因为我在 App 组件状态中有 language 并且当路由更改时 - 我想要 1)App 状态自动更改,2)孩子们从顶级 App 组件接收新道具。 ......... 正如我所看到的 - 现在 - 我将不得不手动更改状态,检查位置,App :(
    • 恕我直言,将 newLang 存储到状态中是不必要的。只需将逻辑移动到渲染方法。 render() { const lang = this.props.location.pathname.split('/').shift(); ... }
    • 我看到了这里的逻辑,但它仍然对我不起作用。而且原因是我靠路由器改component for the page content。但与此同时,这个component for page content 必须从端点提取数据......而且它不知道关于它的语言。 (我的错误是我以为它会自动从App 组件中获取它,但事实并非如此。)
    • 我问了一个关于我的问题的更具体的问题......显然我最初的想法是不正确的。 stackoverflow.com/questions/40510303/…
    猜你喜欢
    • 2020-03-30
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2021-02-25
    • 2021-11-05
    相关资源
    最近更新 更多