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

前端之家收集整理的这篇文章主要介绍了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);
原文链接:https://www.f2er.com/react/300662.html

猜你在找的React相关文章