在 React-Router v4 中以编程方式导航 [英] Programmatically navigating in React-Router v4
问题描述
在使用 React Router V4
完成一些验证后,如何移动到新页面?我有这样的事情:
How can I move to a new page after some validation is done with React Router V4
? I have something like this:
export class WelcomeForm extends Component {
handleSubmit = (e) => {
e.preventDefault()
if(this.validateForm())
// send to '/life'
}
render() {
return (
<form className="WelcomeForm" onSubmit={this.handleSubmit}>
<input className="minutes" type="number" value={this.state.minutes} onChange={ (e) => this.handleChanges(e, "minutes")}/>
</form>
)
}
}
我想将用户发送到另一条路线.我查看了重定向,但它似乎会从我不想要的历史记录中删除当前页面.
I would like to send the user to another route. I had a look at Redirect but it seems like it would delete the current page from the history which I don't want.
推荐答案
您正在使用 react-router v4,因此您需要将 withRouter 与您的组件访问历史对象的属性,然后使用 history.push
动态更改路由.
You are using react-router v4, so you need to use withRouter with your component to access the history object’s properties, then use history.push
to change the route dynamically.
您可以访问历史对象的属性和最近的通过 withRouter 高阶组件匹配.带路由器每次路由随着与渲染道具相同的道具:{匹配,位置,历史}.
You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as render props: { match, location, history }.
像这样:
import {withRouter} from 'react-router-dom';
class WelcomeForm extends Component {
handleSubmit = (e) => {
e.preventDefault()
if(this.validateForm())
this.props.history.push("/life");
}
render() {
return (
<form className="WelcomeForm" onSubmit={this.handleSubmit}>
<input className="minutes" type="number" value={this.state.minutes} onChange={ (e) => this.handleChanges(e, "minutes")}/>
</form>
)
}
}
export default withRouter(WelcomeForm);
这篇关于在 React-Router v4 中以编程方式导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!