react-router-dom之 history+路由url更新页面不刷新的解决办法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react-router-dom之 history+路由url更新页面不刷新的解决办法相关的知识,希望对你有一定的参考价值。

参考技术A 使用方法:

解决 react-router / react-router-dom v4 history不能访问的问题

首先使用router
import React, { Component } from \'react\';
import { BrowserRouter, Route } from \'react-router-dom\';
import { Provider } from \'mobx-react\';
import stores from \'../store/index\';
import Bundle from \'../components/bundle\';
import Hello from \'bundle-loader?lazy!../components/hello.jsx\';
 
// 这是按需加载,对于现在讨论的问题没有影响
const HelloAPP = () => (
    <Bundle load={Hello}>
        {(Hello) => <Hello />}
    </Bundle>
);
export default class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <Provider { ...stores }>
        <BrowserRouter basename="/">
          <Route path="/" component={HelloAPP}/>
        </BrowserRouter>
      </Provider>
    );
  };
}

  接着是子组件的使用history

import React, { Component } from \'react\';
// 需要这步,你要npm 这个,
import PropTypes from \'prop-types\';
export default class Hello extends Component {
  constructor(props) {
    super(props);
  }
  // 这一步是重点
  static contextTypes = {
    router: PropTypes.object.isRequired
  };
  test = () => {
    console.log(this.context);
    setTimeout(() => {
      this.context.router.history.push("/otherPath");
    }, 1000);
  };
  render() {
    return (
      <div>
        <button onClick={this.test}>按钮</button>
      </div>
    );
  };
}

  让我们看看this.context :

以上是关于react-router-dom之 history+路由url更新页面不刷新的解决办法的主要内容,如果未能解决你的问题,请参考以下文章