繁体   English   中英

在 ReactJS 中完成验证后如何重定向页面

[英]How to redirect a page after validation is done in ReactJS

一旦我点击下一步按钮,我就在反应中使用多步表单,它会重定向到下一步,但现在我也想验证表单,所以一旦验证完成,就需要重定向到下一步。 这是我的代码:

import React, { useState } from 'react';  
import SimpleReactValidator from 'simple-react-validator';

const UserDetails = ({ setForm, formData, navigation }) => {
     const {
    fullName
    } = formData;
    const useForceUpdate = () => useState()[1];
    const validator = new SimpleReactValidator();

    const forceUpdate = useForceUpdate();
    const submitForm = (e) =>{  
        e.preventDefault()

        if (validator.allValid()) {
          alert('You submitted the form and stuff!');
        } else {

            validator.showMessages();
           forceUpdate();
        }
      }
      {validator.showMessages('fullName', fullName, 'required|alpha')}
      {validator.showMessages('fullName', fullName, 'required|alpha')}
return( 
<>
<input
type="text"
name="fullName"
placeholder='Name'
onChange={setForm}
defaultValue={fullName} />
    <label className="form__label" htmlFor ="fullname">Name</label>         
  {validator.message('fullName', fullName, 'required|alpha')}
 <button className="btn green_btn w250 font22"  onClick={submitForm}>
Next </button>
</>

我想要所有数据都验证后

    const { next } = navigation;  

应该启用此代码,然后进入下一步..

使用 react-router 中的 useHistory 挂钩。完成所有验证后,将下一页的路径名添加到其中。

import React, { useState } from 'react';  
import SimpleReactValidator from 'simple-react-validator';
import { useHistory } from 'react-router-dom';

const UserDetails = ({ setForm, formData, navigation }) => {
     const {
    fullName
    } = formData;
    const useForceUpdate = () => useState()[1];
    const validator = new SimpleReactValidator();
    const history=useHistory()
    const forceUpdate = useForceUpdate();
    const submitForm = (e) =>{  
        e.preventDefault()

        if (validator.allValid()) {
          history.push('/pathname for nextpage')
          alert('You submitted the form and stuff!');
        } else {

            validator.showMessages();
           forceUpdate();
        }
      }
      {validator.showMessages('fullName', fullName, 'required|alpha')}
      {validator.showMessages('fullName', fullName, 'required|alpha')}
return( 
<>
<input
type="text"
name="fullName"
placeholder='Name'
onChange={setForm}
defaultValue={fullName} />
    <label className="form__label" htmlFor ="fullname">Name</label>         
  {validator.message('fullName', fullName, 'required|alpha')}
 <button className="btn green_btn w250 font22"  onClick={submitForm}>
Next </button>
</>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM