简体   繁体   English

使用setState动态填充对象数组

[英]Using setState to dynamically populate an array of objects

I have an array of Objects in my props from my API but I need to modify the elements in this array of Objects and then pass it to a player on my application. 我的API中的道具中有一个对象数组,但是我需要修改此对象数组中的元素,然后将其传递给应用程序的播放器。 I can successfully get my array of object but when I try to modify the elements and set the data into a state, The new state ends up having just the last item of my list. 我可以成功获取对象数组,但是当我尝试修改元素并将数据设置为状态时,新状态最终仅包含列表的最后一项。 Here is my code, 这是我的代码,

        if(musicitem.musics){
            if(musicitem.musics.length === 0){
                this.setState({musicLimited:true })
            }
            else{
                return musicitem.musics.map((item, index)=>{
                    this.setState({
                        musics:[
                            ...musics,
                            {
                                url:apiConstants.API_MUSIC_FILES+item.url,
                                cover:apiConstants.API_MUSIC_FILES+item.cover,
                                artist:item.artist,

                            }
                        ]
                    })
                });
            }
        }

I expect my state of musics to have an array of newly constructed objects but that is not the case. 我希望我的音乐状态具有一系列新构造的对象,但事实并非如此。 It ends up with just the last object that is expected to be in my array of objects. 它仅以预期在我的对象数组中的最后一个对象结束。 This means that, it has actually loop through the array of objects from props but the next State keeps overriding the previous state. 这意味着,它实际上已经遍历了prop中的对象数组,但是下一个State仍然覆盖了上一个state。

You should mention previous state's property(ie music) to get setState know that while using spread operator. 您应该提及先前状态的属性(即音乐),以使setState在使用传播运算符时知道该状态。

You can access previous state as passing first params to this.setState() . 您可以通过将第一个参数传递给this.setState()来访问先前的状态。

Example : this.setState(prevState => ({ music : [...prevState.music, {artist:item.artist}] })) 示例: this.setState(prevState => ({ music : [...prevState.music, {artist:item.artist}] }))

Your code should be updated like this : 您的代码应像这样更新:

 if(musicitem.musics){
        if(musicitem.musics.length === 0){
            this.setState({musicLimited:true })
        }
        else{
            return musicitem.musics.map((item, index)=>{
                this.setState(prevState => ({
                    musics:[
                        ...prevState.musics, // use prevState
                        {
                            url:apiConstants.API_MUSIC_FILES+item.url,
                            cover:apiConstants.API_MUSIC_FILES+item.cover,
                            artist:item.artist,

                        }
                    ]
                }))
            });
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM