使用e.preventDefault的React handleSubmit(带有axios.post)仍然会刷新

时间:2018-05-13 19:50:41

标签: javascript reactjs

首先或全部...我对React非常非常新,尽管我已经搜索了很多关于这一点的帖子...我仍然没有发现为什么我的页面刷新..任何人都在意看看 ?

我也尝试过e.stopPropagation()和e.nativeEvent.stopImmediatePropagation()但没有成功..

如果您需要其他信息,请与我们联系:

Registration.JS

import React, {
  Component
} from 'react';
//import logo from './logo.svg';
import '../App.css';

const isValidPostalCode = value => /^\d{4}$/.test(value)
const isValidEmail = value => /^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)
const isValidPhone = value => /^\[0-9]{8}$/.test(value)

class Registration extends Component {
  constructor(props) {
    super(props)
    this.state = {
      formData: {
        firstName: "",
        lastName: "",
        email: "",
        phone: "",
        postalCode: "",
      },
      formErrors: {
        firstName: null,
        lastName: null,
        email: null,
        phone: null,
        postalCode: null,
      }
    }
  }

  onFirstNameChange(e) {
    console.log("FN = ", e.target.value)
    this.setState({
      formData: {
        ...this.state.formData,
        firstName: e.target.value
      },
    })
  }
  onLastNameChange(e) {
    this.setState({
      formData: {
        ...this.state.formData,
        lastName: e.target.value
      },
    })
  }
  onEmailChange(e) {
    const {
      value
    } = e.target

    this.setState({
      formData: {
        ...this.state.formData,
        email: value,
      },
      formErrors: {
        ...this.state.formErrors,
        email: isValidEmail(value) ? null : "Legg inn gyldig epost",
      }
    })
  }
  onPhoneChange(e) {
    const {
      value
    } = e.target

    this.setState({
      formData: {
        ...this.state.formData,
        phone: e.target.value
      },
      formErrors: {
        ...this.state.formErrors,
        phone: isValidPhone(value) ? null : "Telefonnummeret må være 8 tall",
      }
    })
  }
  onPostalCodeChange(e) {
    const {
      value
    } = e.target

    this.setState({
      formData: {
        ...this.state.formData,
        postalCode: e.target.value
      },
      formErrors: {
        ...this.state.formErrors,
        postalCode: isValidPostalCode(value) ? null : "Postnummer må være 4 tall",
      }
    })
  }
  render() {
    console.log("logging props in registration", this.props)
    return ( <
      form onSubmit = {
        (e) => {
          this.props.handleSubmit(e, this.state.formData.firstName, this.state.formData.lastName, this.state.formData.email, this.state.formData.phone, this.state.formData.postalCode)
        }
      } >
      <
      div className = "page-content" >
      <
      h3 > Registrering < /h3>

      <
      span > {
        this.props.trumfData.registrationintro
      } <
      /span>

      <
      span className = "registration-block" >
      <
      div className = "registration-block-line" >
      <
      input type = "text"
      placeholder = "Fornavn"
      onChange = {
        (e) => this.onFirstNameChange(e)
      }
      value = {
        this.props.trumfData.firstname ? this.props.trumfData.firstname : this.state.formData.firstName
      }
      /> <
      input type = "text"
      placeholder = "Etternavn"
      onChange = {
        (e) => this.onLastNameChange(e)
      }
      value = {
        this.state.formData.lastName
      }
      /> <
      /div> <
      div className = "registration-block-line" >
      <
      input type = "text"
      placeholder = "Epost"
      onChange = {
        (e) => this.onEmailChange(e)
      }
      value = {
        this.state.formData.email
      }
      /> {
        this.state.formErrors.email
      } <
      /div> <
      div className = "registration-block-line" >
      <
      input type = "text"
      placeholder = "Telefon"
      onChange = {
        (e) => this.onPhoneChange(e)
      }
      value = {
        this.state.formData.phone
      }
      /> {
        this.state.formErrors.phone
      } <
      input type = "text"
      placeholder = "Postnr"
      onChange = {
        (e) => this.onPostalCodeChange(e)
      }
      value = {
        this.state.formData.postalCode
      }
      /> <
      /div> <
      /span> {
        " "
      } {
        this.props.trumfData.isauthenticatd && < input type = "checkbox" > Kryss av... < /input>
      } <
      input type = "submit"
      value = "Registrer din stemme" / >

      <
      /div> <
      /form>
    );
  }
}

export default Registration;

APP.JS

handleSubmit(e, firstName, lastName, email, phone, postalCode) {
  alert('Submitted: ' + firstName + ", " + lastName);
  e.preventDefault();
  e.stopPropagation();
  e.nativeEvent.stopImmediatePropagation();
  this.setState({
    step: 3,
    ...this.state.userVote,
    FirstName: firstName,
    LastName: lastName,
    Email: email,
    MobileNumber: phone,
    ZipCode: postalCode
  })
  axios.post('http://localhost:54467/api/poll/vote', this.state.userVote)
    .then(response => {
      console.log("VI HAR SENDT INN !!!:", response.data)
      // this.setState({ trumfdata: response.data })
    })
    .catch(err => console.log("Error", err))
}

1 个答案:

答案 0 :(得分:1)

解决方案:将e.preventDefault()添加到表单的onSubmit属性

form onSubmit = {
    (e) => {
      e.preventDefault();
      this.props.handleSubmit(e, this.state.formData.firstName, this.state.formData.lastName, this.state.formData.email, this.state.formData.phone, this.state.formData.postalCode)
    }
  } >

但是为什么会这样? preventDefault()只需要成为你做的第一件事,否则你冒险尝试在你有机会之前阻止你运行的任何事件阻止它。我制作了一个代码来说明我的意思:https://codepen.io/anon/pen/odfgavb

[编辑]我提供的上一个答案是错误的。真正的问题可能在于将功能作为道具传递下来。我不能确定。如果有人知道为什么请在这里发布答案。