How do I add an item to the front of a state array in React

后端 未结 3 1986
迷失自我
迷失自我 2021-01-13 00:24

I know that you can add items to the end of the array with concat but how do I unshift to add an item to the front?

Add to the end:

var         


        
相关标签:
3条回答
  • 2021-01-13 00:37

    If you want to modify the original array, use Array.unshift

    var arr = [1,2,3];
    arr.unshift(0);
    arr // 0,1,2,3
    

    If you want a new array, use Array.concat as Alexander suggested

    this.setState({statusData: [0].concat(this.state.statusData)})
    

    Which is similar to spreading into a new array

    this.setState({statusData: [0, ...this.state.statusData]})
    
    0 讨论(0)
  • 2021-01-13 00:53

    Actually you can use .concat in this case,

    var newStatuses = [data.statuses].concat(allStatuses);
    
    0 讨论(0)
  • 2021-01-13 01:02

    Is there a problem doing

    [data.statuses].concat(allStatuses);
    

    If you are using ES6, you can do

    var newStatuses = [data.statuses, ...allStatuses]
    
    0 讨论(0)
提交回复
热议问题