關(guān)于react-router/react-router-dom v4 history不能訪問問題的解決
前言
最近把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 :
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
React Native 資源包拆分實(shí)戰(zhàn)分析
這篇文章主要為大家介紹了React Native 資源包拆分實(shí)戰(zhàn)分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08React.js組件實(shí)現(xiàn)拖拽排序組件功能過程解析
這篇文章主要介紹了React.js組件實(shí)現(xiàn)拖拽排序組件功能過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04React如何利用Antd的Form組件實(shí)現(xiàn)表單功能詳解
這篇文章主要給大家介紹了關(guān)于React如何利用Antd的Form組件實(shí)現(xiàn)表單功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04