【问题标题】:How to add an item to the todo list如何将项目添加到待办事项列表
【发布时间】:2021-12-28 02:51:32
【问题描述】:

这是我的待办事项应用程序中 addItem 函数的快捷方式,我不太明白 slice 在这个 value 中做了什么:this.state.newItem.slice ()。有人可以解释一下吗?非常感谢!

constructor(props) {
    super(props);
    this.state = {
      newItem: "",
      list: []
    };

addItem() {
    // create a new item with unique id
    const newItem = {
      id: 1 + Math.random(),
  

    **value: this.state.newItem.slice()**

 
    };

    // copy current list of items
    const list = [...this.state.list];

    // add the new item to the list
    list.push(newItem);

    // update state with new list, reset the new item input
    this.setState({
      list,
      newItem: ""
    });
  }

【问题讨论】:

  • freeCodeCamp 有一个关于 .slice() 函数的非常酷的课程,请查看freecodecamp.org/learn/…
  • 我认为在这个例子中,对 String 对象进行切片是非常没用的。通常,要在 React (& Vue) 中更新状态数组,使用 slice(方法不同,但功能相似)、map、concat 和 filter 方法返回一个全新的数组,因为改变状态数组可能会导致错误。不过,String 对象不需要它。

标签: reactjs slice setstate


【解决方案1】:

由于slice 返回新字符串,slice 可能已用于复制上述代码中的字符串。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

【讨论】:

    【解决方案2】:

    首先你为什么使用切片方法?如果你用它来削减你的价值。您使用 trim() 方法从字符串的两侧删除空格。 trim() 方法不会更改原始字符串。句法。 string.trim().

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      • 2020-04-17
      • 2021-05-09
      • 2019-10-05
      • 2012-08-20
      相关资源
      最近更新 更多