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

后端 未结 3 2019
迷失自我
迷失自我 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]})
    

提交回复
热议问题