简体   繁体   中英

state is cleared, but input field text is not after form is submitted in React

I am doing exercise on a simple todo App, the user can type their todos in the field, and hit submit to see it added to the todo-list.

I've managed to clear the state once the form is submitted with 'this.setState({newTodo: ''})' (indicated by hitting submit again will add an empty todo-item);

however, the text in the input field will not be cleared.

const TodoItem = ({ text }) => <li>{text}</li>;

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

    this.state = {
        todos: ['walk dog', 'feed cat'],
        newTodo: ''
};

this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(e) {
    e.preventDefault();

    const todos = [...this.state.todos, this.state.newTodo];

    this.setState({ todos, newTodo: '' });
}

render() {
    const { newTodo } = this.state; 
    const todos = this.state.todos.map((todo, index) => <TodoItem key={index} text={todo} />);

    return (
        <div className="App">
            <form onSubmit={this.handleSubmit}>
                <h1>Simple Todo App</h1>

                <input
                    type="text"
                    name="newTodo"
                    value={this.newTodo}

                    onChange={e => this.setState({ [e.target.name]: e.target.value })}
                />

                <ol>
                  {todos}
                </ol>
                <button>SAVE</button>
            </form>
        </div>
    );
}
}

export default App;

Thanks for any kind of help.

this.newTodo is undefined, use this.state.newTodo instead od this.newTodo :

<input
     type="text"
     name="newTodo"
     value={this.state.newTodo} 
      onChange={e => this.setState({ [e.target.name]: e.target.value })}
/>

OR:

const { newTodo } = this.state; 
<input
     type="text"
     name="newTodo"
     value={newTodo} 
      onChange={e => this.setState({ [e.target.name]: e.target.value })}
/>

The reason you see empty newTodo added because your newTodo initial state is empty and in handleSubmit you are always passing it irrespective of whether it's is empty or not. So In handleSubmit check newTodo state and then add newTodo to todos array.

 if(this.state.newTodo != “”){
      const todos = [...this.state.todos, this.state.newTodo];
 }

and change input field value attribute value to newTodo

 <input value={newTodo} />

Don't use this.newTodo

In the following section:

<input
 type="text"
 name="newTodo"
 value={this.newTodo}
 onChange={e => this.setState({ [e.target.name]: e.target.value })}
/>

Change value={this.newTodo} to value={this.state.newTodo}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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