2017-06-16 90 views
0

我想在對象數組上使用this.setState,但是,我的代碼只能設置1對象的狀態。我認爲它是在自己寫作。this.setState與映射寫入本身

路徑:MongoDB

"careerHistoryPositions": [ 
    { 
     "company": "Company A", 
     "title": "Title A", 
     "uniqueId": "1497575516964" 
    }, 
    { 
     "company": "Company B", 
     "title": "Title B", 
     "uniqueId": "1497575525034" 
    } 
    ] 

路徑:Reactpage

constructor(props) { 
    super(props); 

    this.state = { 
     data: [], 
    }; 
    } 

componentWillReceiveProps(nextProps) { 
    const profileCandidateCollection = nextProps.profileCandidate; 
    const profileCandidateCollectionId = profileCandidateCollection._id; 
    const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions; 

    if(careerHistoryPositions) { 
     careerHistoryPositions.map((position) => 
     this.setState({ 
     data: [{ 
      'position.uniqueId': position.uniqueId || '', 
      'position.company': position.company || '', 
      'position.title': position.title || '' 
     }] 
     }) 
    ); 
    } 
    } 
+0

您* *從數組對象改變data'的'值。這就是你告訴JavaScript要做的事情。你想要發生什麼?也許你的意思是做'this.setState({data:careerHistoryPositions.map(...)})''而不是? –

+0

現在,您正在告訴JavaScript將'data'設置爲一個對象的數組。這裏沒有魔術發生。 '數據'就是你正在設置的。 –

+0

有一個未知數量的'careerHistoryPositions'需要被映射。它可能是1或它可能是20.我需要設置數據的狀態,以便我可以使用表單。 – bp123

回答

1

請注意,set狀態不會立即調用,s其次,你用新狀態覆蓋數據。其次,多次設置狀態會重新渲染,效率低下。

停止覆蓋,您可以使用擴展運算符。例如:

a = [1,2,3] 
b = [...a, 4,5] 
//b = [1,2,3,4,5] 

所以翻譯給你的代碼,它應該是這樣的:

this.setState({ 
     data: [...this.state.data, { 
      'position.uniqueId': position.uniqueId || '', 
      'position.company': position.company || '', 
      'position.title': position.title || '' 
     }] 
     }) 

這仍然是低效的,因爲你正在通話狀態多次。 我要改變它看起來像這樣:

if(careerHistoryPositions) { 
     const newData = careerHistoryPositions.map((position) => 
     ({ 
      'position.uniqueId': position.uniqueId || '', 
      'position.company': position.company || '', 
      'position.title': position.title || '' 
     })); 
     this.setState({ 
      data: newData 
     }) 
} 
+0

嘗試你最後的建議,我得到'意外的令牌,預計,'錯誤 – bp123

+0

錯過了對象的{}括號。嘗試新版本。 –

+0

這似乎是最好的答案,但他們都工作。謝謝大家的幫助。 – bp123

0
if(careerHistoryPositions) { 
    const data = [ ]; 
    careerHistoryPositions.map((position) => 
    data.push(
{ 
'position.uniqueId': position.uniqueId || '', 
'position.company': position.company || '', 
'position.title': position.title || '' 
}) 
); 

    this.setState({ data, }); 
    } 

這應該工作。我覺得這個方法會更好,而不是地圖功能中多次設置狀態..