这篇文章主要给大家介绍了关于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 :

上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
以上就是有关v4 history不能访问的原因的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号