reactjs – 以编程方式在React-Router v4中导航

在使用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>
        )
    }
}

我想将用户发送到另一条路线.我看了一下Redirect,但似乎它会删除我不想要的历史记录中的当前页面.

您正在使用 react-router v4,因此您需要将 withRouter与您的组件一起使用以访问历史对象的属性,然后使用history.push动态更改路由.

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和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...