简体   繁体   中英

react-router-dom - Difference between link and history.push?

The difference between href and link I understand.

But I want to know the difference between using the link and withrouter with history.push? If I have already accessed the page does history.push retrieve the page in the cache?

Using Link:

<Link className="btn btn-primary" onClick={logout} to="/">
 Log out
</Link>

Using history:

constructor(props) {
        super(props);
        this.handleLogout = this.handleLogout.bind(this);
    };

    handleLogout(e) {
        const { history } = this.props;
        logout()
        history.push("/");

    }
<button type="button" onClick={this.handleLogout}>Log out</button>

With the Link you can navigate to another "page" by wrapping for example a button and do the redirect when clicking. Mostly this is what you probably want to do. But in some cases you want to navigate to another "page" programatically. For example when something changes in your app that has nothing to do with clicking on a button or link.

So you can use history.push to change the url programmatically without the need to click on a button or a link. =)

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