且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式使用react-router进行导航

更新时间:2023-11-22 18:32:46

考虑到您使用 react-router v4

将您的组件与 withRouter 一起使用,并使用道具中的 history.push 来更改路线。只有当你的组件没有收到路由器道具时,你才需要使用 withRouter ,这可能发生在您的组件是由路由器呈现的组件的嵌套子组件,并且您没有将Router支持传递给它,或者当组件根本没有链接到路由器并且从路由呈现为单独的组件时。

Use your component with withRouter and use history.push from props to change the route. You need to make use of withRouter only when your component is not receiving the Router props, this may happen in cases when your component is a nested child of a component rendered by the Router and you haven't passed the Router props to it or when the component is not linked to the Router at all and is rendered as a separate component from the Routes.

import {withRouter} from 'react-router';

class App extends React.Component {
     ...
     componenDidMount() {
        // get isLoggedIn from localStorage or API call
        if (isLoggedIn) {
             // dispatch an action to change the route
             this.props.history.push('/home');
        }
     }
     render() {
         // return login component
         return <Login />
    }
}


export default withRouter(App);




重要提示

如果您使用 withRouter 来阻止更新被
阻止 shouldComponentUpdate ,重要的是 withRouter 包装实现 shouldComponentUpdate
组件。例如,当
使用Redux时:

If you are using withRouter to prevent updates from being blocked by shouldComponentUpdate, it is important that withRouter wraps the component that implements shouldComponentUpdate. For example, when using Redux:

//这大概是 shouldComponentUpdate

withRouter(connect(...)(MyComponent))

//这不是

connect(...)(withRouter(MyComponent))


或者你可以使用Redirect

or you could use Redirect

import {withRouter} from 'react-router';

class App extends React.Component {
     ...
     render() {
         if(isLoggedIn) {
              return <Redirect to="/home"/>
         }
         // return login component
         return <Login />
    }
}

使用 react-router v2或者react-router v3 ,你可以利用 context 动态改变路线,如

With react-router v2 or react-router v3, you can make use of context to dynamically change the route like

class App extends React.Component {
     ...
     render() {
         if (isLoggedIn) {
             // dispatch an action to change the route
             this.context.router.push('/home');
         }
         // return login component
         return <Login />
    }
}

App.contextTypes = {
    router: React.PropTypes.object.isRequired
}
export default App;

或使用

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');