在使用React Router V4进行一些验证后,如何移动到新页面?我有这样的事情:
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> ) } }
您正在使用
react-router v4,因此您需要将
withRouter与您的组件一起使用以访问历史对象的属性,然后使用history.push动态更改路由.
原文链接:https://www.f2er.com/react/300662.htmlYou 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);