如何在react-router v4上获取历史记录?

sto*_*ter 88 reactjs react-router

我有一些小问题从React-Router v3迁移到v4.在v3中我能够在任何地方执行此操作:

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
Run Code Online (Sandbox Code Playgroud)

我如何在第4版中实现这一目标.

我知道withRouter当你在Component中时,我可以使用,特别的,反应上下文或事件路由器道具.但事实并非如此.

我正在寻找v4 中NavigatingOutsideOfComponents的等价性

Pau*_*l S 153

您只需要一个导出history对象的模块.然后,您将在整个项目中导入该对象.

// history.js
import { createBrowserHistory } from 'history'

export default createBrowserHistory({
  /* pass a configuration object here if needed */
})
Run Code Online (Sandbox Code Playgroud)

然后,您将使用该<Router>组件,而不是使用其中一个内置路由器.

// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'

ReactDOM.render((
  <Router history={history}>
    <App />
  </Router>
), holder)
Run Code Online (Sandbox Code Playgroud)
// some-other-file.js
import history from './history'
history.push('/go-here')
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用`HashRouter`,请导入`createHashHistory`. (4认同)
  • 当我将历史= {历史}放在路线中并像道具一样传递时,它对我有用 (3认同)
  • @HassanAzzam你可能正在使用react-router V5,这个答案适用于V4,而不是V5。我现在面临着同样的挑战,正在到处寻找,但无法使其发挥作用。组件外部的 History.push 可以工作,但单击链接不再有效。 (3认同)

小智 65

这有效! https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  render () {
    this.props.history;
  }
}

withRouter(MyComponent);
Run Code Online (Sandbox Code Playgroud)

  • 只要你在一个组件中.我不是一个组成部分 (22认同)
  • 谢谢,这是从组件链接到另一条路由的最简单、最直接的方法。我只想补充一点,您需要执行 `this.props.history.push('/some_route');` 才能使其正常工作。 (2认同)

Kon*_*zyb 9

如果您只需要历史对象才能导航到其他组件,则基于此答案

import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 错误,您位于组件内。请参阅接受的答案中的 // some-other-file.js (2认同)

Tom*_*zyk 7

Similiary到接受的答案是什么,你可以做的是使用reactreact-router本身为您提供history对象,它可以在范围文件,然后出口.

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;
}
Run Code Online (Sandbox Code Playgroud)

稍后您导入Component并mount以初始化历史变量:

import { BrowserRouter } from 'react-router-dom';
import { GlobalHistory } from './history';

function render() {
  ReactDOM.render(
    <BrowserRouter>
        <div>
            <GlobalHistory />
            //.....
        </div>
    </BrowserRouter>
    document.getElementById('app'),
  );
}
Run Code Online (Sandbox Code Playgroud)

然后您可以在应用程序安装时导入:

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`
};
Run Code Online (Sandbox Code Playgroud)

我甚至制作了npm包就是这么做的.


Arn*_*las 6

如果您使用的是 redux 和 redux-thunk,最好的解决方案是使用react-router-redux

// then, in redux actions for example
import { push } from 'react-router-redux'

dispatch(push('/some/path'))
Run Code Online (Sandbox Code Playgroud)

查看文档以进行一些配置很重要。