Programmatically navigate using react router

后端 未结 30 2390
無奈伤痛
無奈伤痛 2020-11-21 05:18

With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls t

30条回答
  •  失恋的感觉
    2020-11-21 05:42

    React-Router 4.x Answer :

    On my end, I like to have a single history object that I can carry even outside components. What I like to do is to have a single history.js file that I import on demand, and just manipulate it.

    You just have to change BrowserRouter to Router, and specify the history prop. This doesn't change anything for you except that you have your own history object that you can manipulate as you want.

    You need to install history, the library used by react-router.

    Example usage, ES6 notation :

    history.js

    import createBrowserHistory from 'history/createBrowserHistory'
    export default createBrowserHistory()
    

    BasicComponent.js

    import React, { Component } from 'react';
    import history from './history';
    
    class BasicComponent extends Component {
    
        goToIndex(e){
            e.preventDefault();
            history.push('/');
        }
    
        render(){
            return Previous;
        }
    }
    

    EDIT April 16th, 2018 :

    If you have to navigate from a component that is actually rendered from a Route component, you can also access history from props, like that :

    BasicComponent.js

    import React, { Component } from 'react';
    
    class BasicComponent extends Component {
    
        navigate(e){
            e.preventDefault();
            this.props.history.push('/url');
        }
    
        render(){
            return Previous;
        }
    }
    

提交回复
热议问题