【问题标题】:How to update array of objects in set state [duplicate]如何更新设置状态的对象数组[重复]
【发布时间】:2021-05-15 22:13:52
【问题描述】:

`尝试更新 onClick 中的对象数组。我有两个状态,即数组格式的“initialValue”和“todos”。当我签入反应开发人员工具时,我可以看到有两种状态。任务的流程是用户可以在输入文本框中输入文本,一旦用户单击添加按钮,我希望将其添加为对象数组,我保留了一个布尔字段和 Id 字段。 我面临的问题是我可以正确获得“输入值”。我也得到了对象数组,但不是处于“待办事项”状态,并且值没有以数组格式更新,只有输入值发生了变化。例如: 0{completed:false, id:20, text:abc} 当我单击添加按钮时,数组没有更新为 1{completed:false, id:20, text:cde} ,而是在第 0 个postiton 本身的值正在更新。我在下面添加了代码任何人都可以帮助我实现输出。提前致谢。

`

class TodoForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      InputValue: "",
      todos: [],
    };
    console.log("intialvalue", this.state.InputValue);
  }

  handleChange(e) {
    this.setState({ InputValue: e.target.value });
  }

  handleSubmit(e) {
    //   alert("Form state value" + this.state.initalValue);
    e.preventDefault();
    this.setState([
      ...this.state.todos,
      {
        text: this.state.InputValue,
        completed: false,
        id: Math.random() * 1000,
      },
    ]);
  }
  render() {
    return (
      <div className="Todo">
        <form>
          <input
            type="text"
            value={this.state.InputValue}
            onChange={this.handleChange.bind(this)}
          ></input>
          <button onClick={this.handleSubmit.bind(this)}>Add</button>
        </form>
        <p>{this.state.InputValue}</p>
      </div>
    );
  }
}

export default TodoForm;

【问题讨论】:

  • 感谢以上链接。是的,但上面链接的方法与我的略有不同。

标签: javascript arrays reactjs


【解决方案1】:

您必须更新待办事项状态(不完全是状态)。您没有正确更新状态。应该是这样的:

this.setState({
      todos: [
        ...this.state.todos,
        {
          text: this.state.InputValue,
          completed: false,
          id: Math.random() * 1000
        }
      ]
    });

这里是演示:https://codesandbox.io/s/gracious-mountain-rdubi?file=/src/App.js

【讨论】:

  • @Shubam Verma 非常感谢,学习了如何更新多个 setstate :)
猜你喜欢
  • 2021-12-23
  • 2018-09-18
  • 2020-07-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 2021-01-24
  • 2019-11-08
  • 2022-01-06
相关资源
最近更新 更多