当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 关于react-router/react-router-dom v4 history不能访问问题的解决

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

2018年02月02日  | 移动技术网IT编程  | 我要评论

前言

最近把react-router 升级了一下, 在使用react-router-dom 是,子组件使用this.props.history  找不到了,看看官方文档,找了半天也没找到,因为我是在异步执行完后才跳转页面,需要用到push 或者replace,怎么办啊,国内知识都是你复制我的,我复制你的,都特么垃圾。只能去google,

最终找到了答案:(看代码一目了然)

解决方法

首先使用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 :

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网