Reactjs 如何获取react路由器v4的历史记录?

Reactjs 如何获取react路由器v4的历史记录?,reactjs,react-router,Reactjs,React Router,我在从React路由器v3迁移到v4时遇到了一些小问题。 在v3中,我可以在任何地方执行此操作: import { browserHistory } from 'react-router'; browserHistory.push('/some/path'); 如何在v4中实现这一点 我知道,当您在组件中时,我可以使用hocwith router、react context或event router道具。但我不是这样 我正在寻找v4中的等价物,您只需要有一个导出历史对象的模块。然后在整个项目中

我在从React路由器v3迁移到v4时遇到了一些小问题。 在v3中,我可以在任何地方执行此操作:

import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
如何在v4中实现这一点

我知道,当您在组件中时,我可以使用hoc
with router
、react context或event router道具。但我不是这样


我正在寻找v4中的等价物,您只需要有一个导出
历史
对象的模块。然后在整个项目中导入该对象

//history.js
从“历史记录”导入{createBrowserHistory}
导出默认createBrowserHistory({
/*如果需要,在此处传递配置对象*/
})
然后,您将使用
组件,而不是使用其中一个内置路由器

//index.js
从“react Router dom”导入{Router}
从“/历史记录”导入历史记录
从“./App”导入应用程序
ReactDOM.render((
),持有人)
//some-other-file.js
从“/历史记录”导入历史记录
history.push(“/转到此处”)

反应路由器的特定情况下,使用是一种有效的情况场景,例如

class MyComponent extends React.Component {
  props: PropsType;

  static contextTypes = {
    router: PropTypes.object
  };

  render () {
    this.context.router;
  }
}
您可以通过路由器上下文访问历史记录的实例,例如
this.context.router.history

这很有效!

从“react router dom”导入{withRouter};
类MyComponent扩展了React.Component{
渲染(){
这是历史;
}
}
withRouter(MyComponent);

如果您使用的是redux和redux,则最好的解决方案将使用

查看文档以进行一些配置非常重要


与公认的答案类似,您可以使用
react
react路由器
本身为您提供
history
对象,您可以在文件中对其进行作用域,然后将其导出

history.js

从“React”导入React;
从“react router”导入{withRouter};
//变量,该变量将指向路由器历史记录
让globalHistory=null;
//我们将安装在应用程序顶部的组件
类Spy扩展了React.Component{
建造师(道具){
超级(道具)
globalHistory=props.history;
}
componentDidUpdate(){
globalHistory=this.props.history;
}
render(){
返回null;
}
}
导出const GlobalHistory=withRouter(Spy);
//导出路由器历史记录
导出默认函数getHistory(){
回归全球历史;
}
然后导入组件并装载以初始化历史变量:

从'react router dom'导入{BrowserRouter};
从“/history”导入{GlobalHistory};
函数render(){
ReactDOM.render(
//.....
document.getElementById('app'),
);
}
然后,您可以在安装应用程序后在应用程序中导入:

从“/history”导入getHistory;
导出常数goToPage=()=>(调度)=>{
分派({type:GO_TO_SUCCESS_PAGE});
getHistory().push('/success');//此时,组件可能已装入,我们可以安全地获取'history'`
};
我甚至制作了一个这样的组件。

基于您是否只需要历史对象来导航到其他组件:

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>
  );
}
从“react router dom”导入{useHistory};
函数HomeButton(){
const history=useHistory();
函数handleClick(){
历史推送(“/主页”);
}
返回(
回家吧
);
}
在App.js中

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

 const TheContext = React.createContext(null);

 const App = () => {
   const history = useHistory();

   <TheContext.Provider value={{ history, user }}>

    <Switch>
        <Route exact path="/" render={(props) => <Home {...props} />} />
        <Route
          exact
          path="/sign-up"
          render={(props) => <SignUp {...props} setUser={setUser} />}
        /> ...

谢谢@Chris,但正如我所说,我不在组件中。@Chris在一个实用程序类中,请检查,它可能是redux middlewarere或其他任何我最终使用BrowserRouter作为根组件的最简单方式。这样我就可以使用路由器的应用程序组件。不完全是你要求的,但我有同样的要求,这对我来说已经足够了。非常感谢!目前,使用react-router4,我不得不在history.js中使用这个导入:从“history/createBrowserHistory”导入createBrowserHistory;当我把history={history}放在路径中并像道具一样通过时,它对我很有用。我们可以使用history,并在道具中获取历史,而不是创建单独的文件。此解决方案不适用于我的redux。导入
createHashHistory
如果您使用的是
HashRouter
@HassanAzzam,您可能使用的是react router V5,此答案适用于V4,而不是V5。我现在面临着同样的挑战,我四处寻找,但无法让它发挥作用。组件外的history.push可以工作,但单击链接就不再工作。只要您在组件中。我不在组件中谢谢,这是从组件链接到另一个路由的最简单、最直接的方法。我只想补充一点,您需要执行
this.props.history.push('/some_route')以使其工作。@storm\u buster
const Component=props=>{…//stuff}
export default with router(Component)
适用于无状态组件。具体问题是关于何时在组件外部,因此this.context不能作为选项使用:>“我知道,当您在组件中时,我可以使用hoc with router、react context或event router道具。但我的情况并非如此。“我来这里是希望找到这个确切的解决方案,谢谢你。作为reactjs 16.9的一员,这个解决方案将在componentWillMount和componentWillReceiveProps上发出一个弃用警告。@ian true,修复了这个错误,你在一个组件中。请参阅//some-other-file.js,摘自公认的answeruseHistory(和React Hooks)比公认的答案好/干净得多
 import {useHistory } from "react-router-dom";

 const TheContext = React.createContext(null);

 const App = () => {
   const history = useHistory();

   <TheContext.Provider value={{ history, user }}>

    <Switch>
        <Route exact path="/" render={(props) => <Home {...props} />} />
        <Route
          exact
          path="/sign-up"
          render={(props) => <SignUp {...props} setUser={setUser} />}
        /> ...
const Welcome = () => {
    
    const {user, history} = React.useContext(TheContext); 
    ....