将属性添加到不可变对象

时间:2017-08-17 18:11:25

标签: javascript reactjs immutability

我正在尝试向数组中的对象添加新属性。我的想法是做这样的事情:

class Foo extends Component {
    constructor(props) {
        super(props);

        this.state = this.getInitialState();
        console.log(this.state); //Property "label" is missing in "members" array
    }

    /**
     * Get initial state
     * @returns {{title, description}}
     */
    getInitialState = () => {
        let members = this.props.members.slice();
        members.map((member) => {
            return {
                ...member,
                label: (member.firstName + " " + member.lastName)
            }
        });
        console.log(members); //"label" is not a property of objects

        return {title: "", description: "", responsible: [], typeOf: null, 
                members: members};
    };

    render () {
         return (<div/>)
    }
}

我希望members保持/保持不变,同时为此数组中的每个对象添加另一个属性。我在这做错了什么?谢谢!

2 个答案:

答案 0 :(得分:4)

您没有将map的返回值存储到成员变量

getInitialState = () => {
        let members = this.props.members.map((member) => {
            return {
                ...member,
                label: (member.firstName + " " + member.lastName)
            }
        });
        console.log(members); //"label" is not a property of objects

        return {title: "", description: "", responsible: [], typeOf: null, 
                members: members};
    };

答案 1 :(得分:1)

数组原型.map()不会改变原始数组,但会返回一个新数组。