【问题标题】:React Redirect Post反应重定向帖子
【发布时间】:2019-06-04 18:16:51
【问题描述】:

我正在尝试进行此调用,其中 url 是基本域名,model 是传递到 POST 但用于反应的对象。 (不想在我的反应应用程序中使用 jquery):

$.redirect(url + "external-entrance", model, "POST");

表单信息被发送给第三方,他们正在计算表单中的信息并在他们的网站上向我显示信息。在我当前的解决方案中,我使用 refs 提交表单。但是,我想使用状态,因为我可以更好地验证/屏蔽字段并将信息发送到我自己的后端。但是当我说我不能像ref="form"method="post"action="url"那样做一个帖子重定向时,使用axios post然后windows.location.href它只会把我带到链接但不会发布到它。

import React from 'react'
import axios from 'axios'
import { H3, P } from '../../components/StyledHeading'
import Button from '../../components/Button'


class ContactForm extends React.Component {
  constructor(props) {
  super(props)
  this.state = {
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    zipCode: '',
    errors: [],
  }
  this.textInput = React.createRef();
}

_handleSubmit = evt => {
  evt.preventDefault()
  const payload = {
    "first_name": "Thomas",
    "last_name": "Edison",
    "email": "edison@email.com",
    "phone": "555-555-5355",
    "zip_code": 239062,
  }
  this.refs.myForm.submit();
}

render() {
  return (
    <Container>
      <form ref="myForm" method="post" action="https://externalsite.co/external-entrance">
        <H3>Ready to reserve your spot?</H3>
        <P className="subtitle">Fill out the form below and we&rsquo;ll get in touch soon.</P>
        <div className="inputFieldSection">
          <label>
            First Name:
            <input
              type="text"
              ref={this.textInput}
              disabled={isSending}
              name="firstName"
              placeholder="Thomas"/>
          </label>
          <label>
            Last Name:
            <input
            type="text"
            ref={this.textInput}
            disabled={isSending}
            name="lastName"
            placeholder="Edison"/>
        </label>
        <label>
          Phone Number:
          <input
            type="text"
            ref={this.textInput}
            disabled={isSending}
            name="phoneNumber"
            placeholder="555-555-5555"/>
        </label>
        <label>
          Email address:
          <input
            type="text"
            ref={this.textInput}
            disabled={isSending}
            name="emailAddress"
            placeholder="edison@email.com"/>
        </label>
        <input type="hidden" ref={this.textInput} name="zipCode" value={29006}/>
      </div>
      <Button color={Color.secondaryColor} onClick={this._handleSubmit}>Submit My Reservation</Button>
    </form>
  </Container>
)
}
}

export default ContactForm

【问题讨论】:

    标签: jquery reactjs post


    【解决方案1】:

    在我的估计中,我认为你做错了几件事。

    • 无需创建表单的引用,也无需添加“post”“action”标签添加到表单中。您只需将 "onSubmit" 属性设置为用于进行 API 调用的函数&lt;form onSubmit={this._handleSubmit}&gt;

    • 根据我的第一点,您需要将用于提交表单的表单内的按钮的类型设置为&lt;button type="submit"&gt;&lt;/button&gt;

    • 在声明一个函数时,如果你不使用 ES6,你将不得不在类构造函数中绑定函数(你的 "SendLead()" strong> 函数)如this.SendLead = this.SendLead.bind(this)

    • 最好将表单输入保存在类状态中,这样可以更轻松地执行验证或将其传递给另一个组件或其他任何东西。

    • 您可以在类的构造函数中为状态设置该值,而不是使用隐藏的输入字段。

    • 由于我们将输入字段值保存在状态中,因此您需要为每个输入字段的 "onChange" 事件添加一个函数。 onChange={this._handleInputChange}

    这些是我可以在您的代码中指出的主要内容。我稍微调整了你的让它工作,但基本上我只是做了我上面提到的。

    import React from 'react'
    import axios from 'axios'
    // import { H3, P } from '../../components/StyledHeading'
    // import Button from '../../components/Button'
    
    
    class ContactForm extends React.Component {
      constructor(props) {
        super(props)
        this.state = {
          firstName: '',
          lastName: '',
          email: '',
          phone: '',
          zipCode: 29006,
          errors: [],
        }
      }
    
      SendLead = payload => {
        const URL = "http://localhost:3001/v1"
        const authToken = "Token token=5e2pJ5P234234123"
        const config = { "headers": { Authorization: authToken } }
        const bodyParams = payload
    
        axios.post(`${URL}/leads`, bodyParams, config)
          .then(res => console.log({res}))
          .catch(error => {
            console.log({error})
            this.setState({
              errors: error.response.data,
            })
          })
    
      }
    
      _handleInputChange = e => 
        this.setState({
          [e.target.name]: e.target.value
        })
    
    
      _handleSubmit = evt => {
        evt.preventDefault()
        const {
          firstName,
          lastName,
          email,
          phone,
          zipCode
        } = this.state;
    
        const payload = {
          "first_name": firstName,
          "last_name": lastName,
          "email": email,
          "phone": phone,
          "zip_code": zipCode,
        }
        this.SendLead(payload)
      }
    
      render() {
        const {
          firstName,
          lastName,
          email,
          phone,
          zipCode
        } = this.state;
    
        return (
          <form onSubmit={this._handleSubmit}>
            <h3>Ready to reserve your spot?</h3>
            <p className="subtitle">Fill out the form below and we&rsquo;ll get in touch soon.</p>
            <div className="inputFieldSection">
              <label>
                First Name:
                <input
                  type="text"
                  value={firstName}
                  onChange={this._handleInputChange}
                  // disabled={isSending}
                  name="firstName"
                  placeholder="Thomas" />
              </label>
              <label>
                Last Name:
                <input
                  type="text"
                  value={lastName}
                  onChange={this._handleInputChange}
                  // disabled={isSending}
                  name="lastName"
                  placeholder="Edison" />
              </label>
              <label>
                Phone Number:
                  <input
                  type="text"
                  value={phone}
                  onChange={this._handleInputChange}
                  // disabled={isSending}
                  name="phone"
                  placeholder="555-555-5555"
                />
              </label>
    
              <label>
                Email address:
                  <input
                  type="text"
                  value={email}
                  onChange={this._handleInputChange}
    
                  // disabled={isSending}
                  name="email"
                  placeholder="edison@email.com"
                />
              </label>
              <input type="hidden" name="zipCode" value={29006} />
            </div>
            <button type="submit">Submit My Reservation</button>
          </form>
        )
      }
    }
    
    export default ContactForm
    

    【讨论】:

    • @andre-gomez 这有帮助吗?
    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 1970-01-01
    • 2017-07-01
    • 2023-03-27
    • 2012-10-16
    相关资源
    最近更新 更多