推送方法不返回新数组

时间:2018-12-26 10:11:00

标签: javascript reactjs

我正在通过javascript push()方法向数组添加对象。我的数组是一个对象数组。我想console.log()新数组。但这给了我新数组的长度。我知道push()方法返回新数组的长度,但是我想在应用程序中使用新数组。如何获得

    let sub_sprite = this.state.sub_sprite;
    let updated_sub_subsprite;
    updated_sub_subsprite = sub_sprite.push(this.state.sprite[that.state.sprite_count]);
    console.log(updated_sub_subsprite);

    that.setState({sub_sprite:updated_sub_subsprite}, ()=>{
         console.log(this.state.sub_sprite)
    });

2 个答案:

答案 0 :(得分:1)

请勿在以React组件状态存储的数组上使用Array.push,它将直接使状态发生变化,这可能会导致问题(see this article)。

您可以使用Array.concat创建具有附加值的新数组:

let sub_sprite = this.state.sub_sprite
let updated_sub_subsprite;
updated_sub_subsprite = sub_sprite.concat([this.state.sprite[that.state.sprite_count]]);
console.log(updated_sub_subsprite);
that.setState({sub_sprite:updated_sub_subsprite}, ()=> {
    console.log(this.state.sub_sprite)
})

一种更简洁和方便的方法是使用spread syntax(注意三个点):

let sub_sprite = this.state.sub_sprite
let updated_sub_subsprite;
updated_sub_subsprite = [...sub_sprite, this.state.sprite[that.state.sprite_count]);
console.log(updated_sub_subsprite);
that.setState({sub_sprite:updated_sub_subsprite}, ()=> {
    console.log(this.state.sub_sprite)
})

答案 1 :(得分:0)

Array#push方法不会返回新的数组,而是将项目添加到该数组实例后的the length of the array

Array#concat方法似乎更适合您尝试做的事情,seeing that offers the "appending behavior"并返回结果数组。

考虑对代码进行以下调整,利用concat()来实现所需的功能:

let sub_sprite = this.state.sub_sprite;

// Create a new array via concat(), adding a new array with one item 
// that is [ sub_sprite [that.state.sprite_count] ] to sub_sprite
let updated_sub_subsprite = sub_sprite.concat( [ sub_sprite [that.state.sprite_count] ]);

console.log(updated_sub_subsprite);

that.setState({sub_sprite : updated_sub_subsprite }, ()=>{
    console.log(this.state.sub_sprite)
})