使用 react-router-dom,如何从 React 组件外部访问 browserHistory 对象? [英] Usign react-router-dom, how can I access browserHistory object from outside a React component?

查看:51
本文介绍了使用 react-router-dom,如何从 React 组件外部访问 browserHistory 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以前的 react-router 我能够做到这一点:

import {browserHistory} from 'react-router';

从我的 actionCreators 文件,我可以做这样的事情:

...一些异步操作已完成(例如,用户成功登录).browserHistory.push('/dashboard');

但是使用新的 react-router-dom (v4) 似乎我不能再像这样导入 browserHistory 并且访问历史对象的唯一方法是从 React 组件道具

this.props.history

在使用 react-router-dom 完成异步 redux 操作后,将我的用户重定向到新页面的方法是什么?

解决方案

withRouter 就是您要找的.

"您可以通过 访问历史对象的属性和最接近的匹配项withRouter 高阶组件."

import React, { PropTypes } from 'react'从反应路由器"导入 { withRouter }//一个简单的组件,显示当前位置的路径名class ShowTheLocation 扩展了 React.Component {静态 propTypes = {匹配:PropTypes.object.isRequired,位置:PropTypes.object.isRequired,历史:PropTypes.object.isRequired}使成为() {const { 匹配,位置,历史} = this.props返回 (<div>您现在位于 {location.pathname}</div>)}}//创建一个连接"的新组件(借用 redux//术语)到路由器.const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

With the previous react-router I was able to do this:

import {browserHistory} from 'react-router';

from my actionCreators file and I could do something like this:

...some async action completed (for example, user logged in successfully)..
browserHistory.push('/dashboard');

But with the new react-router-dom (v4) it seems like I can no longer import browserHistory just like that and that the only way to access the history object is from a React components props

this.props.history

What would be a way to redirect my user to a new page after an async redux action has completed using react-router-dom?

解决方案

withRouter is what you're looking for.

"You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component."

import React, { PropTypes } from 'react'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

这篇关于使用 react-router-dom,如何从 React 组件外部访问 browserHistory 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆