如何解决React-对象数组-根据输入更新对象属性
我正在创建锻炼日志应用程序,但在更新状态的嵌套属性时遇到问题。这是我的状态...
this.state = {
chosenExercises: [
{
id: 1,name: "Barbell Bench Press",type: "Strength",setCount: [1],lbs: [],reps: []
},{
id: 2,name: "Dumbell Bench Press",reps: []
}
]
} //End of state
//Function to update lbs from user input
updateLbs = (lbs) => {
//WHAT GOES HERE??
}
用户输入的内容向下为2个组件,它是父组件中表单的一部分。是否有可能通过上级组件中的变更处理程序来更新每个练习的每磅重量,以作为道具传递下来?
完成特定练习后,这就是我要寻找的结果。
this.state = {
chosenExercises: [
{
id: 1,setCount: [1,2,3,4],lbs: [135,135,155,185],reps: [12,12,10,8]
},reps: []
}
]
}
我试图一起使用.find()和.filter(),但是我还不够好。感谢您的协助。
解决方法
只是示例如何更新lbs功能。我的想法是找到一个需要更新并更新它们的对象,在为selectedExercises设置状态之后,通过向其他对象附加一个更新的对象。
//Function to update lbs from user input
updateLbs = (lbs,id) => {
//WHAT GOES HERE??
let chosenExercise = this.state.chosenExercises.find(chosenExercise => chosenExercise['id'] === 1);
if (chosenExercise === undefined)
return;
//update lbs
chosenExercise['lbs'] = lbs;
let remainChosenExercise = this.state.chosenExercises.filter(chosenExercise => chosenExercise['id'] !== 1);
this.setState({chosenExercise: [...remainChosenExercise,chosenExercise]});
}
,
您需要某种标识符才能知道您要更新的内容。无论是索引位置还是名称(假设名称是唯一的)还是ID。在下面的示例中,我假设您正在通过lbs更新传递练习的名称。
update = (lbs,name) => {
setState((prevState) => {
const update = {...prevState};
const index = update.chosenExcercises.findIndex((excercise) => excercise.name === name)
update[index] = {
...update[index],lbs: [...update[index].lbs,lbs]
}
return {chosenExcercises: update}
})
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。