我的状态对象看起来像这样:
getInitialState: function(){
return {
people: [
{'id': 1, 'first': "Jake", 'last': "A", 'title': "Associate", 'company': "Twitter", 'stage': "Onsite"},
{'id': 2, 'first': "Graham", 'last': "R", 'title': "Eng", 'company': "GitHub", 'stage': "Recruiter"}
],
}
},
如果我想访问杰克的记录并更改公司名称,我将如何专门选择他?
updateCandidate: function() {
this.setState({
....how do I pick Jake's company and change it to Google?
)}
)
快速更新:
1。)将id添加到州
2。)这个辅助函数:
var RenderPeople = React.createClass({
change: function(e) {
var id = this.props.user.id
var user = this.props.user
this.props.updateCandidate(id, user, e.target.value)
},
var Dashboard = React.createClass({
getInitialState: function(){
return {
people: [
{'id': 1, 'first': "Jake", 'last': "A", 'title': "Associate", 'company': "Twitter", 'stage': "Onsite"},
{'id': 2, 'first': "Graham", 'last': "R", 'title': "Eng", 'company': "GitHub", 'stage': "Recruiter"}
],
}
},
updateCandidate:function(id, user, newStage){
this.state.people.map(val => {
if(val['id'] === id){
console.log(val); // this works!
console.log(newStage); //this works!
this.setState({
[val['stage']] : newStage
}, function() {'this ran'});
}
})
},
由于某种原因this.setState
没有运行。有什么理由吗?
答案 0 :(得分:2)
通过people数组映射,当您找到first
值等于Jake的元素时,使用Spread语法({ ...}
)返回修改后的对象。
const newPeople = people.map(val => {
if(val['first'] === "Jake"){
return { ...val, val['company']: 'Google'};
}
});
//EDIT:
// call setState after the call to map is complete:
this.setState({people: newPeople}):