Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - How to change the state in react with a form

I have a form that is supposed to update the initial state, I've followed many tutorials and my code looks the same as them but for some reason it doesn't update the state.

import React, { Component } from 'react';

class Create extends Component{
   constructor(props){
      super(props);

      this.state = {
         title: "",
         body: "",
         error: ""
      } 
   }

   onTitleChange(e) {
      const title = e.target.value;
      this.setState({title})
   }

   onBodyChange(e) {
      const body = e.target.value;
      this.setState({body})
   }

   onSubmit(e) {
      e.preventDefault();

      if(!this.state.title || !this.state.body){
         this.setState(() => ({ error: "Please fill in all gaps"}))
      } else {
         this.setState(() => ({ error: "" }))
         // Send info to the main page
         alert(this.state.title);
      }
   }

   render(){
      return(
         <div>
         {this.state.error && <p>{this.state.error}</p>}
         <form onSubmit = {this.onSubmit}>
         <label>Put a title for your note</label>
         <input 
            placeholder="Title"
            type="text"
            value={this.state.title}
            autoFocus
            onChange= {this.onTitleChange}
         />
         <label>Write your note</label>
         <textarea 
            placeholder="Note"
            value={this.state.body}
            autoFocus
            onChange = {this.onBodyChange}
         />
         <input type="submit" value="Submit"/>
         </form>
         </div>
      );
   }
}

export default Create;

When I check the current state in the React developer tools it shows that the state remains the same and I don't know why because there are not errors in the log. I'm working with webpack, babel and react.

//////////////////// EDITED ////////////////////

I edited my code following the suggestions you guys gave me but still it doesn't work. An alert is supposed to appear when submitted the form but that doesn't get fired either, so I believe that non of the functions are getting fired.

This is my edited code:

import React, { Component } from 'react';

class Create extends Component{
   constructor(props){
      super(props);
      this.onTitleChange = this.onTitleChange.bind(this);
      this.onBodyChange = this.onBodyChange.bind(this);
      this.onSubmit = this.onSubmit.bind(this);

      this.state = {
         title: "",
         body: "",
         error: ""
      } 
   }

   onTitleChange(e) {
      const title = e.target.value;
      this.setState((prevState) => {
         return {
           ...prevState,
           title
         };
       });
   }

   onBodyChange(e) {
      const body = e.target.value;
      this.setState((prevState) => {
         return {
           ...prevState,
           body
         };
       });
   }

   onSubmit(e) {
      e.preventDefault();

      if(!this.state.title || !this.state.body){
         this.setState((prevState) => {
            return {
              ...prevState,
              error: "Please fill in all gaps"
            };
          });
      } else {
         this.setState((prevState) => {
            return {
              ...prevState,
              error: ""
            };
          });
         // Send info to the main page
         alert(this.state.title);
      }
   }

   render(){
      return(
         <div>
         {this.state.error && <p>{this.state.error}</p>}
         <form onSubmit = {this.onSubmit}>
         <label>Put a title for your note</label>
         <input 
            placeholder="Title"
            type="text"
            value={this.state.title}
            autoFocus
            onChange= {this.onTitleChange}
         />
         <label>Write your note</label>
         <textarea 
            placeholder="Note"
            value={this.state.body}
            autoFocus
            onChange = {this.onBodyChange}
         />
         <input type="submit" value="Submit"/>
         </form>
         </div>
      );
   }
}

export default Create;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should try binding the event handlers in the constructor, because it seems like this within those event handling functions could be undefined. The React documentation outlines why the binding is necessary, and here's another useful page on handling forms in React.

constructor(props) {
  super(props);

  ...
  this.onTitleChange = this.onTitleChange.bind(this);
  this.onBodyChange = this.onBodyChange.bind(this);
  this.onSubmitChange = this.onSubmitChange.bind(this);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...