在当前版本的React Router(v3)中,我可以接受一个服务器响应,并使用browserHistory.push
转到适当的响应页面。然而,这在v4中是不存在的,我不确定处理这个问题的适当方式是什么。
在这个例子中,使用Redux,_components/app-product-form.js_在用户提交表单时调用this.props.addProduct(props)
。当服务器返回成功时,用户被带到购物车页面。
// actions/index.js
export function addProduct(props) {
return dispatch =>
axios.post(`${ROOT_URL}/cart`, props, config)
.then(response => {
dispatch({ type: types.AUTH_USER });
localStorage.setItem('token', response.data.token);
browserHistory.push('/cart'); // no longer in React Router V4
});
}
如何让React Router v4的函数重定向到Cart页面?
React Router v4与v3(以及更早的版本)有根本的不同,你不能像以前那样做browserHistory.push()
。
如果你想了解更多信息,本讨论似乎与此有关。
创建一个新的browserHistory
不会起作用,因为<BrowserRouter>
会创建自己的历史实例,并监听其变化。所以不同的实例会改变网址,但不会更新<BrowserRouter>
。
browserHistory
在v4中没有被react-router暴露,只有在v2中。相反,你有几个选项可以做到这一点。
withRouter
高阶组件相反,你应该使用`withRouter'高阶组件,并将其包裹在将推送到历史的组件上。比如说。
<!-- language: lang-js -->
import React from "react";
import { withRouter } from "react-router-dom";
class MyComponent extends React.Component {
...
myFunction() {
this.props.history.push("/some/Path")。
}
...
}
export default withRouter(MyComponent);
查看官方文档以获得更多信息。
context
的API使用context可能是最简单的解决方案之一,但作为一个实验性的API,它是不稳定的,也不被支持。只有在其他一切都失败时才使用它。这里有一个例子。
<!-- language: lang-js -->
import React from "react";
import PropTypes from "prop-types";
class MyComponent extends React.Component {
static contextTypes = {
路由器。PropTypes.object
}
构造函数(props, context) {
super(props, context);
}
...
myFunction() {
this.context.router.history.push("/some/Path")。
}
...
}
请看一下关于context的[官方文档](https://reactjs.org/docs/context.html)。
如果你希望你的应用程序是稳定的,不要使用context。它是一个实验性的API,在未来的React版本中,它很可能会被破坏。
如果你不顾这些警告而坚持使用上下文,请尽量将你对上下文的使用隔离在一个小范围内,并尽可能避免直接使用上下文API,以便在API发生变化时更容易升级。
我是这样做的。
import React, {Component} from 'react';
export default class Link extends Component {
constructor(props) {
super(props);
this.onLogout = this.onLogout.bind(this);
}
onLogout() {
this.props.history.push('/');
}
render() {
return (
<div>
<h1>Your Links</h1>
<button onClick={this.onLogout}>Logout</button>
</div>
);
}
}
使用this.props.history.push('/cart');
来重定向到购物车页面,它将被保存在历史对象中。
祝您愉快,迈克尔。
this.context.history.push
将无法工作。
我设法让推送工作像这样进行。
static contextTypes = {
router: PropTypes.object
}
handleSubmit(e) {
e.preventDefault();
if (this.props.auth.success) {
this.context.router.history.push("/some/Path")
}
}