首页 > 解决方案 > react-router-dom - 链接和history.push之间的区别?

问题描述

我理解href和link之间的区别。

但是我想知道将链接和withrouter与history.push一起使用的区别?如果我已经访问过该页面,history.push 是否会在缓存中检索该页面?

使用链接:

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

使用历史:

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>

标签: reactjsreact-routerreact-router-v4react-router-dom

解决方案


使用链接,您可以通过包装例如按钮导航到另一个“页面”,并在单击时进行重定向。大多数情况下,这是您可能想要做的。但在某些情况下,您希望以编程方式导航到另一个“页面”。例如,当您的应用程序发生与单击按钮或链接无关的更改时。

因此,您可以使用 history.push 以编程方式更改 url,而无需单击按钮或链接。=)


推荐阅读