Prevent react-router history.push from reloading current route

前端 未结 5 1621
青春惊慌失措
青春惊慌失措 2021-02-19 08:55

I\'m taking my first steps with react-router.

I\'m currently using the hashHistory for development purposes and I\'m performing \'manual\' nav

5条回答
  •  太阳男子
    2021-02-19 09:27

    I will give this a shot...

    If you land here and looking to change your URL (for sharing purposes for example) then RR docs already has the solution described. Just make sure you do not use the history within the component (i.e. this.props.history.push())as you will be (as expected) routed to the target. You are however allowed to access your browser history without any interference with the component's history.

    Following tested only on Chrome

    // history.js
    import { createBrowserHistory } from 'history'
    export default createBrowserHistory()
    

    and then from your XYZ component

    // XYZ.js
    import React from 'react';
    import history from './history'
    
    class XYZ extends React.Component {
        _handleClick() {
            // this should not cause rerender and still have URL change 
            history.push("/someloc");
        }
        render() {
            return(
              
            )
        }
    }
    

    Hope it helps someone else.

提交回复
热议问题