与接受的答案类似,您可以使用react和react-router它本身为您提供history可以在文件中确定范围然后导出的对象。
历史.js
import React from 'react';
import { withRouter } from 'react-router';
// variable which will point to react-router history
let globalHistory = null;
// component which we will mount on top of the app
class Spy extends React.Component {
  constructor(props) {
    super(props)
    globalHistory = props.history; 
  }
  componentDidUpdate() {
    globalHistory = this.props.history;
  }
  render(){
    return null;
  }
}
export const GlobalHistory = withRouter(Spy);
// export react-router history
export default function getHistory() {    
  return globalHistory;
}
然后导入 Component 并挂载以初始化历史变量:
import { BrowserRouter } from 'react-router-dom';
import { GlobalHistory } from './history';
function render() {
  ReactDOM.render(
    <BrowserRouter>
        <div>
            <GlobalHistory />
            //.....
        </div>
    </BrowserRouter>
    document.getElementById('app'),
  );
}
然后您可以在安装后导入您的应用程序:
import getHistory from './history'; 
export const goToPage = () => (dispatch) => {
  dispatch({ type: GO_TO_SUCCESS_PAGE });
  getHistory().push('/success'); // at this point component probably has been mounted and we can safely get `history`
};
我什至制作了npm 包来做到这一点。