React.js - 在状态中为数组添加值的最佳方法是什么

Fli*_*ion 48 memory state reactjs

我有一个状态数组,让我们说这个.state.arr.我想在此属性中添加一些内容,然后更改一些属性.

选项1

onChange(event){
    this.state.arr.push('newvalue');
    ...
    this.setState({some:'val',arr:this.state.arr})
}
Run Code Online (Sandbox Code Playgroud)

选项2

onChange(event){
    var newArr = this.state.arr;
    ...
    newArr.push('newvalue');
    ...
    this.setState({some:'val',arr:newArr})
}
Run Code Online (Sandbox Code Playgroud)

所以..我知道this.state应该被视为不可变的.但是可以像在选项1中那样使用它,我仍然从中设置状态,或者我需要使用类似选项2的东西,因此总是首先在内存中复制

Kut*_*lan 69

目前,这是最好的方法.

this.setState(previousState => ({
    myArray: [...previousState.myArray, 'new value']
}));
Run Code Online (Sandbox Code Playgroud)

  • 如果我希望“新值”成为我传入的参数。我是否只需执行```onChange = (id) => { this.setState(prevState => ({ tags: [...prevState.tags, ID] })); }``` (2认同)

But*_*ers 57

您提供的两个选项都是相同的.它们都仍指向内存中的同一对象并具有相同的数组值.您应该将状态对象视为不可变,但是您需要重新创建数组,使其指向新对象,设置新项,然后重置状态.例:

onChange(event){
    var newArray = this.state.arr.slice();    
    newArray.push("new value");   
    this.setState({arr:newArray})
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么要用切片? (3认同)
  • Slice将创建数组的新浅表副本,使其不可变。 (2认同)

Jam*_*ieD 40

如果您使用的是ES6语法,则可以使用扩展运算符将新项目作为单个线条添加到现有阵列中.

// Append an array
const newArr = [1,2,3,4]
this.setState(prevState => ({
  arr: [...prevState.arr, ...newArr]
}));

// Append a single item
this.setState(prevState => ({
  arr: [...prevState.arr, 'new item']
}));
Run Code Online (Sandbox Code Playgroud)


小智 35

带钩的短路useState

const [value, setValue] = useState([])
setValue([...value, newvalue])
Run Code Online (Sandbox Code Playgroud)


Tia*_*oLr 20

使用concat的另一种简单方法:

this.setState({
  arr: this.state.arr.concat('new value')
})
Run Code Online (Sandbox Code Playgroud)

  • 我发现这是最具表现力和最简洁的方法. (5认同)
  • 将此更改为已接受的答案,因为它不仅是最后一个冗长的答案,而且根据 jsperf,它也是最快的解决方案 (3认同)

小智 8

现在最好的离开。

this.setState({ myArr: [...this.state.myArr, new_value] })
Run Code Online (Sandbox Code Playgroud)


vin*_*h10 6

对于带有挂钩的功能组件

const [searches, setSearches] = useState([]);

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query));

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query));

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query]);

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query]);

Run Code Online (Sandbox Code Playgroud)

来源:https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc


小智 5

onChange() {
     const { arr } = this.state;
     let tempArr = [...arr];
     tempArr.push('newvalue');
     this.setState({
       arr: tempArr
    });
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Run Code Online (Sandbox Code Playgroud)