在下面的示例中,我想在单击提交后将输入字段重置为空字符串:https ://codesandbox.io/s/todo-app-object-vk99c
表单.js:
class Form extends Component {
state = {
todo: { name: "" }
// inputValue: ""
};
onChange = (e) => {
const newTodo = {
id: Math.random() * 10000,
name: e.target.value,
completed: false
};
this.setState({
todo: newTodo
});
};
onSubmit = async (e) => {
e.preventDefault();
this.props.addTodo(this.state.todo);
console.log(this.state.todo, "this.state.todo 1");
await this.setState({
todo: {}
});
console.log(this.state.todo, "this.state.todo 2");
};
render() {
return (
<form className="Form">
<input
type="text"
className="input"
onChange={this.onChange}
value={this.state.todo.name}
/>
<button className="submit" onClick={this.onSubmit}>
Submit
</button>
{this.state.todo.name}
</form>
);
}
}
export default Form;
应用程序.js:
addTodo = (newTodo) => {
const newState = [...this.state.todos, newTodo];
this.setState({
todos: newState
});
};
我的问题是:
我想将
name
字符串更新为空字符串,如果它不是输入字段的一部分,它似乎可以工作。为什么会这样?在我点击提交之前:https ://imgur.com/hONqktR ,在我点击提交之后:https ://imgur.com/HwL6FZT (注意按钮旁边的文本如何submit
重置为空字符串,那么为什么 React 更新一个地方的状态,而不是另一个?)我收到以下警告:
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
at input
at form
at Form (https://vk99c.csb.app/src/Components/Form/Form.js:50:34)
at div
at App (https://vk99c.csb.app/src/App.js:51:34)
我认为这是相当模糊的。我知道表单(这是 React 中的受控输入)是问题所在,但不明白警告告诉我什么,以及如何解决它。
更新: 我相信这段代码与它有关:
onSubmit = async (e) => {
e.preventDefault();
this.props.addTodo(this.state.todo);
console.log(this.state.todo, "this.state.todo 1");
await this.setState({
todo: {
name: {}
}
});
console.log(this.state.todo, "this.state.todo 2");
};
当我更改{}
为 时""
,它起作用了,并且警告消失了,但是,我仍然不明白为什么它会在一个地方起作用而在另一个地方不起作用,以及警告在说什么。
编辑: 我得到了这个答案React - changed an uncontrolled input 的建议,但这不是我的情况,因为我的初始状态不是 Form.js 中的空对象
todo: { name: "" }