這篇文章主要介紹了react-router/react-router-dom v4 history不能訪問怎么辦,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
創(chuàng)新互聯(lián)主營蘆山網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,App定制開發(fā),蘆山h5微信小程序搭建,蘆山網(wǎng)站營銷推廣歡迎蘆山等地區(qū)企業(yè)咨詢
前言
最近把react-router 升級了一下, 在使用react-router-dom 是,子組件使用this.props.history 找不到了,看看官方文檔,找了半天也沒找到,因?yàn)槲沂窃诋惒綀?zhí)行完后才跳轉(zhuǎn)頁面,需要用到push 或者replace,怎么辦啊,國內(nèi)知識都是你復(fù)制我的,我復(fù)制你的,都特么垃圾。只能去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';
// 這是按需加載,對于現(xiàn)在討論的問題沒有影響
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);
}
// 這一步是重點(diǎn)
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 :

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“react-router/react-router-dom v4 history不能訪問怎么辦”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!
分享題目:react-router/react-router-domv4history不能訪問怎么辦
網(wǎng)頁URL:http://chinadenli.net/article10/ppcodo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、自適應(yīng)網(wǎng)站、App設(shè)計(jì)、商城網(wǎng)站、網(wǎng)站營銷、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)