【问题标题】:Usign react-router-dom, how can I access browserHistory object from outside a React component?使用 react-router-dom,如何从 React 组件外部访问浏览器历史对象?
【发布时间】:2017-08-31 20:29:08
【问题描述】:

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

import {browserHistory} from 'react-router';

从我的 actionCreators 文件中,我可以执行以下操作:

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

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

this.props.history

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

【问题讨论】:

    标签: reactjs redux react-router react-redux react-router-dom


    【解决方案1】:

    withRouter 就是你要找的东西。

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

    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)
    

    【讨论】:

    • 但是如果我想在 redux-thunk 或 redux-saga 中使用历史对象呢?不在反应组件内
    • 所以最后我所做的是在异步操作完成时将 redux state 属性更改为 true(可以说它称为“userLogged”)。我将容器组件包装在“withRouter”中,并在“componentWillReceiveProps”方法中检查“userLogged”属性是否为真,然后使用历史对象推送新路由。
    • 实际上我在 react router 网站示例中找到了一种方法来做我想做的事情。看起来你可以在 render() 方法上返回一个 组件,所以如果是真的,你可以在 render() 方法中检查“userLogged”是否为真,而不是检查“componentWillReceiveProps”中的“userLogged”是否为真像这样: if (userLogged) return 这是示例的链接:reacttraining.com/react-router/web/example/auth-workflow
    • 能够导入 browserHistory 并执行 browserHistory.push('whereIWantToGo') 非常简单和直接。 v3 和 v4 之间发生的任何事情似乎都是过度工程
    猜你喜欢
    • 2017-08-01
    • 2018-12-26
    • 2018-07-20
    • 1970-01-01
    • 2017-03-17
    • 2017-12-29
    • 1970-01-01
    • 2017-08-17
    • 2019-12-15
    相关资源
    最近更新 更多