Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 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 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...