-
class组件
引入withRouter
包裹组件
import { withRouter } from 'react-router-dom'
class Nav extends Component {
//...
componentDidMount() {
this.props.history.push('/xxx')
}
}
export default withRouter(Nav)
-
函数组件
1.引入useHistory
或者2.引入withRouter
1.引入useHistory
import { useHistory } from "react-router-dom"
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>Go home</button>
)
}
2.引入withRouter
import { withRouter } from 'react-router-dom'
function HomeButton(props) {
//....
props.history.push('/xxxx')
}
export default withRouter(HomeButton)
网友评论