您好,登錄后才能下訂單哦!
這篇文章主要介紹了react-router/react-router-dom v4 history不能訪問(wèn)怎么辦,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
前言
最近把react-router 升級(jí)了一下, 在使用react-router-dom 是,子組件使用this.props.history 找不到了,看看官方文檔,找了半天也沒(méi)找到,因?yàn)槲沂窃诋惒綀?zhí)行完后才跳轉(zhuǎn)頁(yè)面,需要用到push 或者replace,怎么辦啊,國(guó)內(nèi)知識(shí)都是你復(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'; // 這是按需加載,對(duì)于現(xiàn)在討論的問(wèn)題沒(méi)有影響 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 這個(gè), 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不能訪問(wèn)怎么辦”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。