react-router-dom - 链接和 history.push 之间的区别?

Hia*_*lli 5 reactjs react-router react-router-v4 react-router-dom

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

但是我想知道使用link和withrouter和history.push的区别?如果我已经访问过该页面,history.push 会检索缓存中的页面吗?

使用链接:

<Link className="btn btn-primary" onClick={logout} to="/">
 Log out
</Link>
Run Code Online (Sandbox Code Playgroud)

使用历史:

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>
Run Code Online (Sandbox Code Playgroud)

wei*_*alk 16

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

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

  • 这是唯一的区别吗?它们在什么情况下使用?从功能上来说它们是相同的吗? (3认同)