猿问

在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,但似乎它将从我不想要的历史记录中删除当前页面。


慕村225694
浏览 1076回答 3
3回答

jeck猫

您可以使用withRouter将history对象作为属性注入的高阶组件。然后,您可以history.push用来进行重定向:import { withRouter } from 'react-router-dom';...class WelcomeForm extends Component {&nbsp; &nbsp; handleSubmit = (e) => {&nbsp; &nbsp; &nbsp; &nbsp; e.preventDefault()&nbsp; &nbsp; &nbsp; &nbsp; if(this.validateForm())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.props.history.push('/life');&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <form className="WelcomeForm" onSubmit={this.handleSubmit}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input className="minutes" type="number" value={this.state.minutes} onChange={ (e) => this.handleChanges(e, "minutes")}/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }}export default withRouter(WelcomeForm);要进行重定向,您还可以<Redirect to="/someURL" />在某些情况下使用,但是必须渲染此组件,因此您必须在JSX中的某个位置使用它。
随时随地看视频慕课网APP
我要回答