简体   繁体   中英

React Router - Is there an 'easier' way to route to a new path besides using Context?

Is there an easier or perhaps more recent way to be able to, for instance, click on a button and onClick of that button, reroute to a new path?

....BESIDES using the context method on the component?

Thanks

There are ways:

1. withRouter - HoC from react-router (higher-order component) that wraps another component to provide props.router

import { withRouter } from 'react-router';

class App extends Component {
   ...
    onClickButton(){
      this.props.router.push('/path')
    }
   ...
}

export default withRouter(App);

2. History singleton (hashHistory / browserHistory)

import { hashHistory} from 'react-router';

class App extends Component {
   ...
    onClickButton(){
      hashHistory.push('/path')
    }
   ...
}

3.Also you can get history from props in component, wich is passed to route

....
<Route path="/" component={App} />

then in Component

class App extends Component {
   ...
    onClickButton(){
      this.props.history.push('/path')
    }
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM