2017-08-17 63 views
0

我試圖添加一個新的屬性到數組中的對象。我的想法是做這樣的事情:React將屬性添加到不可變的對象

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留/保持不變,但這個陣列中添加另一個屬性對每個對象。我在這裏做錯了什麼?謝謝!

回答

3

你不存儲返回地圖的價值,成員變量

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}; 
    }; 
+0

哇,現在我覺得啞巴。謝謝。已解決 – Nocebo

+1

我會;)必須等5分鐘 – Nocebo

+1

@Nocebo在回答中添加了一個編輯,以顯示由於Array#map已經返回一個新數組,因此不必使用this.props.members。切片()'。 – philraj

1

數組原型.map()不發生變異原數組,而是返回一個新的數組。

+0

感謝您的信息。將查找它:) – Nocebo