加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:41:00 所属栏目:百科 来源:网络整理
导读:在使用React Router V4进行一些验证后,如何移动到新页面?我有这样的事情: export class WelcomeForm extends Component { handleSubmit = (e) = { e.preventDefault() if(this.validateForm()) // send to '/life' } render() { return ( form className="
在使用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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读