首页 > 解决方案 > 反应站点导航无需重新加载

问题描述

需要无需重新加载页面即可导航。

例如,通过单击按钮或链接从代码中的某个位置

export default class Test1 extends React.Component {

    constructor(props) {
        super(props);

        this.onClick = this.onClick.bind(this);
    }

    onClick() {
        this.props.history.push('/my-path')
    }

    render() {
        return (
            <a className={this.props.className} onClick={this.onClick}>{this.props.children}</a>
            <input type="button" onClick={this.onCLick} value="halo2"/>
        );
    }

}

但是 this.props.history 是未定义的。

export default withRouter(Test1);

产生错误

Error: Invariant failed: You should not use <withRouter(Test1) /> outside a <Router>

通过像这里创建额外的历史类达到最积极的效果如何在 react-router v4 上获取历史?

但它只会更改 URL 而不会实际移动到该位置(不呈现也不执行预期的事件)。

更新 1

甚至尝试将历史推送到全局变量

class DebugRouter extends BrowserRouter {
    constructor(props) {
        super(props);
        App.history = this.history;

然后

App.history.push('/my path');

它也只更改 URL。页面和事件没有变化

标签: reactjsreact-routerbrowser-history

解决方案


我通常Link'react-router-dom'.

所以你可以<a>改为<Link to='/path'>Text</Link>

还要确保您的整个应用程序都在提供程序内部,<BrowserRouter>否则它们都不起作用。

这是如何使用它的有用链接:https ://reactrouter.com/web/guides/quick-start


推荐阅读