微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我不能在 React 中正确更新嵌套状态?

如何解决为什么我不能在 React 中正确更新嵌套状态?

在下面的这个例子中,我想在点击提交后将输入字段重置回空字符串:https://codesandbox.io/s/todo-app-object-vk99c

Form.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;

App.js:

 addTodo = (newTodo) => {
    const newState = [...this.state.todos,newTodo];
    this.setState({
      todos: newState
    });
  };

我的问题是:

  1. 我想将 name 字符串更新为空字符串,如果它不是输入字段的一部分,它似乎可以工作。为什么会这样? 在我点击提交之前:https://imgur.com/hONqktR , 单击提交后:https://imgur.com/HwL6FZT(注意 submit 按钮旁边的文本如何重置为空字符串,那么为什么 React 在 1 个位置而不是另一个位置更新状态?)

  2. 我收到以下警告:

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 - changing an uncontrolled input 的建议,但这不是我的情况,因为我的初始状态不是 Form.js 中的空对象

todo: { name: "" }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。