使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
当前回答
对于当前的React版本(15.3),this.props.history.push('/location');对我有用,但它显示了以下警告:
browser.js:49警告:[creact router]props.history和context.hhistory已弃用。请使用context.router。
我用context.router解决了这个问题:
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.backPressed = this.backPressed.bind(this);
}
backPressed() {
this.context.router.push('/back-location');
}
...
}
MyComponent.contextTypes = {
router: React.PropTypes.object.isRequired
};
export default MyComponent;
其他回答
如果您使用的是更新版本的React,那么使用“useHistory”钩子是最好的选择。
React路由器v2
对于最新版本(v2.0.0-rc5),推荐的导航方法是直接推到历史单例。您可以在组件外部导航文档中看到这一点。
相关摘录:
import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
如果使用更新的react router API,则需要在组件内部使用this.props中的历史记录,以便:
this.props.history.push('/some/path');
它还提供pushState,但对于每个记录的警告,它都是不推荐的。
如果使用react router redux,它提供了一个推送功能,您可以这样调度:
import { push } from 'react-router-redux';
this.props.dispatch(push('/some/path'));
然而,这可能仅用于更改URL,而不是实际导航到页面。
以下是最简单、最干净的方法,大约是当前的React Router 3.0.0和ES6:
使用ES6反应路由器3.x.x:
import { withRouter } from 'react-router';
class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};
// Export the decorated class
export default withRouter(Example);
或者,如果不是默认类,则导出如下:
withRouter(Example);
export { Example };
注意,在3.x.x中,<Link>组件本身使用router.push,因此您可以传递任何传递<Linkto=标记的内容,例如:
this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'
React路由器v4和ES6
您可以使用Router和this.props.history.push。
import {withRouter} from 'react-router-dom';
class Home extends Component {
componentDidMount() {
this.props.history.push('/redirect-to');
}
}
export default withRouter(Home);
只需使用this.props.history.push('/where/to/go');