我有以下示例代码,用于了解扩展运算符和更新反应状态。我理解它是如何工作的,但我不完全理解return {...inst, hobbies}
语法如何更新嵌套的爱好数组。
我的困惑是因为当我使用hobbies.slice(hobbyIndex,1)
而不是hobbies.splice(hobbyIndex,1)
时,虽然传入了不同的hobbyIndex值,但我的爱好数组不会改变事件。
我的期望是,如果我的hobbyIndex值为0,那么爱好应该只是数组中从索引0到1的值,所以基本上是数组中的第一个元素。我的控制台日志确认了这一点。但是,当我的应用程序运行时,爱好的值仍然与随机选择的教师的爱好列表中的值相同。为什么?
this.state = {
instructors: [
{
name: "Jimmy",
hobbies: ['soccer','reading','sports']
},
{
name: "Paul",
hobbies: ['sailing','skiing','diving']
},
{
name: "Sam",
hobbies: ['eating','sleeping','TV']
},
]
};
const randInst = Math.floor(Math.random() * this.state.instructors.length);
const hobbyIndex = Math.floor(Math.random() * this.state.instructors[randInst].hobbies.length);
const instructors = this.state.instructors.map((inst,idx) => {
if (idx === randInst) {
const hobbies = [...inst.hobbies];
//hobbies.splice(hobbyIndex,1); //this works to remove the specified index
hobbies.slice(hobbyIndex,1); //this works in terms of console.log showing the expected value based on the hobbyIndex value
console.log("value of random selected hobby and hobbies to return: ", hobbyIndex, hobbies);
return {...inst,hobbies} //inst object's hobbies array seems to update when splice is used, but not when slice is use...
}
return inst;
});