gpt4 book ai didi

reactjs - 使用react-router-dom,如何从React组件外部访问浏览器History对象?

转载 作者:行者123 更新时间:2023-12-03 13:43:08 27 4
gpt4 key购买 nike

使用之前的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组件 Prop

this.props.history

使用react-router-dom完成异步redux操作后,如何将用户重定向到新页面?

最佳答案

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)

关于reactjs - 使用react-router-dom,如何从React组件外部访问浏览器History对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43244498/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com