向处于状态的数组中添加值的最佳方法是什么

我在 state 中有一个数组,比如 this. state.arr。 我想向这个 state 属性添加一些内容,然后更改其他一些属性。

选择一

onChange(event){
this.state.arr.push('newvalue');
...
this.setState({some:'val',arr:this.state.arr})
}

选择二

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

So.. I know this.state is supposed to be treated immutable. But is it ok to use it like in option 1 where I still set the state from it, or do I need to go with something like option 2, and thus always first making a copy in memory

335140 次浏览

Both of the options you provided are the same. Both of them will still point to the same object in memory and have the same array values. You should treat the state object as immutable as you said, however you need to re-create the array so its pointing to a new object, set the new item, then reset the state. Example:

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

For now, this is the best way.

this.setState(previousState => ({
myArray: [...previousState.myArray, 'new value']
}));

Another simple way using concat:

this.setState({
arr: this.state.arr.concat('new value')
})

If you are using ES6 syntax you can use the spread operator to add new items to an existing array as a one liner.

// 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']
}));

If you want to keep adding a new object to the array i've been using:

_methodName = (para1, para2) => {
this.setState({
arr: this.state.arr.concat({para1, para2})
})
}
handleValueChange = (value) => {
let myArr= [...this.state.myArr]
myArr.push(value)
this.setState({
myArr
})

This might do the work.

the best away now.

this.setState({ myArr: [...this.state.myArr, new_value] })

onChange() {
const { arr } = this.state;
let tempArr = [...arr];
tempArr.push('newvalue');
this.setState({
arr: tempArr
});
}
<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>

This might not directly answer your question but for the sake of those that come with states like the below

 state = {
currentstate:[
{
id: 1 ,
firstname: 'zinani',
sex: 'male'


}
]


}

Solution

const new_value = {
id: 2 ,
firstname: 'san',
sex: 'male'


}

Replace the current state with the new value

 this.setState({ currentState: [...this.state.currentState, new_array] })

For functional components with hooks

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]);


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

Short way with useState hook:

const [value, setValue] = useState([])
setValue([...value, newvalue])

React hook - useState (2022)

const [array, setArray] = useState([]);


const handleChange = (newValue) => {
setArray((array) => [...array, newValue]);
};