【问题标题】:state is cleared, but input field text is not after form is submitted in React状态已清除,但在 React 中提交表单后输入字段文本没有
【发布时间】:2018-07-04 05:50:03
【问题描述】:

我正在做一个简单的待办事项应用程序,用户可以在字段中输入他们的待办事项,然后点击提交以查看它是否已添加到待办事项列表中。

一旦使用 'this.setState({newTodo: ''})' 提交表单,我已经设法清除状态(再次点击提交将添加一个空的待办事项);

但是,输入字段中的文本不会被清除。

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;

感谢您的任何帮助。

【问题讨论】:

  • 将输入字段值属性更改为 value={newTodo}。不要使用 this.newTodo。
  • @HemadriDasari 非常感谢您解决了这个问题!
  • 只是更改 value={newTodo} 解决了您的问题?我不这么认为,因为您将空的 newTodo 状态传递给 handleSubmit 中的 todos 数组,这将创建空的 todo-item

标签: javascript reactjs state


【解决方案1】:

this.newTodo 未定义,使用 this.state.newTodo 代替 od this.newTodo

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

或者:

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

【讨论】:

  • 非常感谢,我刚刚意识到除了 this.state 之外,newTodo 从未作为单独的道具存在。非常感谢!
【解决方案2】:

你看到空的 newTodo 添加的原因是因为你的 newTodo 初始状态是空的,并且在 handleSubmit 中你总是传递它,不管它是否为空。所以在 handleSubmit 中检查 newTodo 状态,然后将 newTodo 添加到 todos 数组中。

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

并将输入字段值属性值更改为newTodo

 <input value={newTodo} />

不要使用 this.newTodo

【讨论】:

  • 感谢您指出这一点,我实际上刚刚意识到 newTodo 仅存在于 this.state 中,而不是类 App 上的属性。谢谢!
【解决方案3】:

在以下部分:

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

value={this.newTodo} 更改为value={this.state.newTodo}

【讨论】:

  • 感谢您指出这一点,我实际上刚刚意识到 newTodo 仅存在于 this.state 中,而不是类 App 上的属性。谢谢!
猜你喜欢
  • 2020-09-11
  • 1970-01-01
  • 2018-03-14
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 2019-05-23
  • 2023-03-09
  • 1970-01-01
相关资源
最近更新 更多