这篇文章主要给大家介绍了关于react-router/react-router-dom v4 history不能访问问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧。
前言
最近把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 ( <p> <button onclick={this.test}>按钮</button> </p> ); };}
让我们看看this.context :
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
利用node.js等技术如何实现登录注册功能?
在vue中如何使用filter过滤器
前端算法中有关文字避让的问题(详细教程)
以上就是有关v4 history不能访问的原因的详细内容。