Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

reactjs - browserHistory.push doesn't navigate to new page

I've set up browserHistory on a router with this (react-router 2.0):

import { browserHistory } from 'react-router'

function requireAuth(nextState, replace) {
    if (!services.auth.loggedIn()) {
        replace({
            pathname: '/login',
            state: { nextPathname: nextState.location.pathname }
        })
    }
}

export default (store) => (
  <Router history={browserHistory}>
    <Route path='/' component={AppLayout}>
      <Route path="login" component={LoginContainer} />
      <Route path="map" component={MapContainer} onEnter={requireAuth} />
    </Route>
  </Router>
);

I'm then trying to use browserHistory in react-router to programmatically route to a new page from a view, ala:

 import { browserHistory } from 'react-router'

 ...

 browserHistory.push('/map');

This changes the URL to /map but does not render the components in that route. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned in my comment I was having this same problem, but I've found a way to make it work.

What's happening here is your Route is changing, but your AppLayout component isn't actually updating it's state automatically. The Router doesn't seem to automatically force a state change on the component. Basically, this.state.children on your AppLayout is not being updated with the new children.

The solution that I found (and, full disclosure, I don't know if this is how you're supposed to achieve this, or if it's best practice) is to use the componentWillReceiveProps function and update this.state.children with the children from the new props:

componentWillReceiveProps(nextProps) {
    this.setState({
        children: nextProps.children
    });
}

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...