简体   繁体   English

React - 在组件状态的数组内向对象添加属性

[英]React - Adding a property to an object inside of array in component's state

I am fetching an array of objects in the state, and I am trying to add a property to each of these objects. 我正在获取状态中的一个对象数组,我正在尝试为每个对象添加一个属性。
The problem is I can see my property being added to each of the objects but when I mapping through all these objects and trying to console.log it I'm getting undefined 问题是我可以看到我的属性被添加到每个对象,但是当我映射所有这些对象并尝试console.log ,我得到了undefined

Adding a property 添加属性

addFavourites() {
        let data = this.state.data.map((e) => {
            e.favourite = false;
            return e;
        });
        return data;
    }
state = {
        data: []
    }

addFavourites's called here: addFavourites在这里调用:

getItem = () => {
        this.service
            .mergeData()
            .then((body) => {
                this.setState({
                    data: body
                },
                () => {
                    this.addFavourites();
                },
                () => {
                    this.dataToFilter();
                });
            });
    }

    componentDidMount(){
        this.getItem();
    }

In render function I see all my objects including favourite 在渲染功能中,我看到我的所有对象,包括收藏

console.log(data.map((e) => e));

But this gives an array of undefined 但这给出了一个未定义的数组

console.log(data.map((e) => e.favourite));

How can I solve this? 我怎么解决这个问题?

First, welcome! 首先,欢迎! You should have probably made it more clear that this question is about React. 您应该更清楚地知道这个问题是关于React的。

Now to the answer, every state modification would be made using setState , so your addFavourites function should be like this: 现在回答,每个状态修改都是使用setState ,所以你的addFavourites函数应该是这样的:

addFavourites() {
    let data = this.state.data.map((e) => {
        e.favourite = false;
        return e;
    });
    this.setState({ data: data });
}

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

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