【发布时间】: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 对象不需要它。