在react-router v2和v3中,我们可以做到
import React, { Component, PropTypes } from "react";
class PostsNew extends Component {
static contextTypes = {
router: PropTypes.object
}
handleUserSubmit(props) {
this.props.createPost(props)
.then(() => {
// the post has been created successfully
// now route back to index
this.context.router.push("/");
});
}
// ...
但是在react-router v4中,如果我们需要做的只是this.props.history.push()
而不是使用context
:
handleUserSubmit(props) {
this.props.createPost(props)
.then(() => {
// the post has been created successfully
// now route back to index
this.props.history.push("/");
});
}
那么我们可以跳过PropTypes
的导入和contextTypes
的定义吗?因此,如果我们使用react-router v4,那么改变路径就像this.props.history.push("/");
一样简单。