解決 react-router / react-router-dom v4 history不能訪問的問題

首先使用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>
    );
  };
}

  接着是子組件的使用historyreact

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 (
      <div>
        <button onClick={this.test}>按鈕</button>
      </div>
    );
  };
}

  讓咱們看看this.context :npm

相關文章
相關標籤/搜索