最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Serialize <form> data in React JS to submit POST request - Stack Overflow

programmeradmin4浏览0评论

I have a very basic ment form that takes some text input from a user and sends a POST request via AJAX to create a new ment.

var CommentForm = React.createClass({
  propTypes: {
    // ...
    // ...
  },

  handleFormSubmit: function(e) {
    e.preventDefault();

    var ponent = this;

    return $.ajax({
      type: "POST",
      url: this.props.someURL,
      data: // ???? - Need to figure out how to serialize data here,
      dataType: "json",
      contentType: "application/json",
      success: (function(response){ alert("SUCESS") }),
      error: (function(){ alert("ERROR"); })
    });
  },

  render: function() {
    var ponent = this;

    return (
      <form onSubmit={ponent.handleFormSubmit} className="ments__form" id="new_ment" accept-charset="UTF-8">
        // ...
      </form>
    );
  }
});

I need to serialize the form data to send along with my POST request, but I'm not sure how. I know in JQuery I can select the form element and do something like $("#my_form").serialize(), but I can't seem to call that from inside the React ponent (not sure why?)

Some other stackoverflow answers suggested adding a ref='foo' to each relevant DOM element and then I can access them with React.findDOMNode(this.refs.foo).getValue();. This works fine but it leaves me to manually construct the whole serialized form data string, which isn't pretty if the form is a lot longer and plex.

// Sample serialized form string
"utf8=✓&authenticity_token=+Bm8bJT+UBX6Hyr+f0Cqec65CR7qj6UEhHrl1gj0lJfhc85nuu+j2YhJC8f4PM1UAJbhzC0TtQTuceXpn5lSOg==&ment[body]=new+ment!"

Is there a more idiomatic way to approach this - perhaps a helper that will let me serialize my form data within ReactJS?

Thanks!

I have a very basic ment form that takes some text input from a user and sends a POST request via AJAX to create a new ment.

var CommentForm = React.createClass({
  propTypes: {
    // ...
    // ...
  },

  handleFormSubmit: function(e) {
    e.preventDefault();

    var ponent = this;

    return $.ajax({
      type: "POST",
      url: this.props.someURL,
      data: // ???? - Need to figure out how to serialize data here,
      dataType: "json",
      contentType: "application/json",
      success: (function(response){ alert("SUCESS") }),
      error: (function(){ alert("ERROR"); })
    });
  },

  render: function() {
    var ponent = this;

    return (
      <form onSubmit={ponent.handleFormSubmit} className="ments__form" id="new_ment" accept-charset="UTF-8">
        // ...
      </form>
    );
  }
});

I need to serialize the form data to send along with my POST request, but I'm not sure how. I know in JQuery I can select the form element and do something like $("#my_form").serialize(), but I can't seem to call that from inside the React ponent (not sure why?)

Some other stackoverflow answers suggested adding a ref='foo' to each relevant DOM element and then I can access them with React.findDOMNode(this.refs.foo).getValue();. This works fine but it leaves me to manually construct the whole serialized form data string, which isn't pretty if the form is a lot longer and plex.

// Sample serialized form string
"utf8=✓&authenticity_token=+Bm8bJT+UBX6Hyr+f0Cqec65CR7qj6UEhHrl1gj0lJfhc85nuu+j2YhJC8f4PM1UAJbhzC0TtQTuceXpn5lSOg==&ment[body]=new+ment!"

Is there a more idiomatic way to approach this - perhaps a helper that will let me serialize my form data within ReactJS?

Thanks!

Share Improve this question asked Aug 13, 2016 at 23:40 user2490003user2490003 11.9k21 gold badges100 silver badges171 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

You would usually use the ponent state to store all the information.

For example, when an inputs text is changed, you would change the state to reflect that:

<input type="text" onChange={ (e) => this.setState({ text: e.target.value }) }

Then, when it es to submit the form you can access the value using this.state.text.

This does mean that you would have to build the object yourself however, although, this could be achieved via a loop:

this.state.map((value, index) => {
  obj[index] = value;
});

and then send obj as the post data.

UPDATE

The only performance issue with updating the state is that the ponent is re-rendered each time. This isn't an issue and is the way react ponents work, as long as you watch for the size of the render method and what it is doing.

Forms in the usual HTML <form> tag sense, don't exist within React. You use the form ponents to change the state. I suggest reading up on React Forms

In terms of the UTF8 flag, that would be the value of a hidden field, so you could use refs in this case to get that value for your object:

<input type="text" ref="utf8" value="✓" />

obj.utf8 = this.refs['utf8'].value

For those who want to use Serialize form in ReactJs with functional ponent try this:

1. Create a state

const [form, setForm] = useState({});

2. Create a function handler

const handleForm = (name, value) => {
     setForm({...form, [name]: value});
}

Now you got your object here:

const handleSubmit = () => {
     console.log(form);
}

3. In your render

<form>
     <input onChange={(e)=>handleForm('name', e.target.value)} />
     <input onChange={(e)=>handleForm('phone', e.target.value)} />
     <button onClick={()=>handleSubmit()}>Submit</button>
</form>

UPDATE 2022

Or use useForm

useForm is a custom hook for managing forms with ease. It takes one object as optional argument. The following example demonstrates all of its properties along with their default values.

发布评论

评论列表(0)

  1. 暂无评论