我想在对象数组上使用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 || ''
}]
})
);
}
}
您* *从数组对象改变data'的'值。这就是你告诉JavaScript要做的事情。你想要发生什么?也许你的意思是做'this.setState({data:careerHistoryPositions.map(...)})''而不是? –
现在,您正在告诉JavaScript将'data'设置为一个对象的数组。这里没有魔术发生。 '数据'就是你正在设置的。 –
有一个未知数量的'careerHistoryPositions'需要被映射。它可能是1或它可能是20.我需要设置数据的状态,以便我可以使用表单。 – bp123